Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename a list of file with names from another list

I have a list like the following, in a file called lista.txt:

mickey
donald
daffy 
bugs

I have a folder containing many files: filename1, filename2, ... filenameN.

I want to iterate through those files to achieve:

filename1 => mickey 
filename2 => donald ...

Can you provide me working sample code for this task?

like image 674
Fabio B. Avatar asked Jul 11 '11 08:07

Fabio B.


4 Answers

It's not my style to do your work for you. I'd rather you post what you've already tried, so I can help you debug it, but this problem is so easy, I'm going to bite anyway.

x=1; for y in $(cat lista.txt); do mv $y filename$x; let x=$x+1; done
like image 188
Flimzy Avatar answered Oct 22 '22 03:10

Flimzy


Using bash arrays:

files=( * )
i=0
while read -r new_name; do
  mv "${files[$i]}" "$new_name"
  (( i++ ))
done < lista.txt
like image 22
glenn jackman Avatar answered Oct 22 '22 05:10

glenn jackman


let "count=1"

for newname in $(cat lista.txt); do
  mv "filename$count" "$newname"
  let "count++"
done
like image 44
Blagovest Buyukliev Avatar answered Oct 22 '22 04:10

Blagovest Buyukliev


I used double redirection with new file descriptors to rename all flac files of a directory according to a given "filelist.txt" this way:

while read -u 9 filename ; do  
    read -u 8 newname 
    echo mv "$filename" "$newname" 
done 9<<<"$(ls -1 *flac)" 8< filelist.txt

Each .flac file name on the directory goes through file descriptor 9 to the variable "filename" while in the same iteration, each line of the filelist.txt goes through file descriptor 8 to the variable "newname".

Yes, one of the new file descriptors could have been avoided and simply use the default standard input (deleting "-u 9" and "9"), but I got used to not use stdin for those; that way you can include a read statement inside the loop for interactivity or control, and it won't be filled by the redirected data.

The echo is for "test-only" and should be deleted after approving the operation.

like image 32
BeGood Avatar answered Oct 22 '22 04:10

BeGood