LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   Renaming files (https://www.linuxquestions.org/questions/linux-general-1/renaming-files-724721/)

mashcaster 05-08-2009 01:19 PM

Renaming files
 
If I have some files

1.txt
2.txt
3.txt
and so on

and I have another text file called "names.txt" which has the text

filenameone.txt
filenametwo.txt
filenamethree.txt
and so on

How do I rename the files based on the text in the "names.txt" file?

dracofhc 05-08-2009 01:49 PM

I would say a shell script would be your best bet. It would open your file then start a for() loop that reads one line from the file (assuming your new file names are on separate lines), then renames the file. Each iteration of the for() loop will grab the next file name from your names.txt file and since the index is incremented it will operate on the next file in line. Sorry this is a little vague, I don't have the time to write the script myself. I hope this points you in the right direction, though.

jan61 05-08-2009 01:52 PM

Moin,

how do you assign the filenames in the directory to the according filenames in names.txt? Simply by the position in the "ls" output?

In this case you can do it like this:
1. create a file with the filename's list:
Code:

ls >/tmp/list.txt
2. merge the two files:
Code:

paste /tmp/list.txt /tmp/names.txt
You get the following 2 column output:
Code:

jan@jack:~/tmp> paste -d " " /tmp/list.txt /tmp/names.txt
1.txt one.txt
2.txt two.txt
3.txt three.txt

3. Now you can use this output to rename the files:
Code:

paste -d " " /tmp/list.txt /tmp/names.txt | while read line; do
  mv $line
done

The filenames may not contain spaces or tabs!

Jan

mk27 05-08-2009 03:14 PM

Quote:

Originally Posted by jan61 (Post 3534852)
3. Now you can use this output to rename the files:

That is so freakin clever I had to thank you just for the trip ;)


All times are GMT -5. The time now is 04:01 PM.