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?
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
Using bash arrays:
files=( * )
i=0
while read -r new_name; do
mv "${files[$i]}" "$new_name"
(( i++ ))
done < lista.txt
let "count=1"
for newname in $(cat lista.txt); do
mv "filename$count" "$newname"
let "count++"
done
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With