Search code examples
bashshrenamemv

rename a file with 2 lists in bash


I have 2 text files, old.txt with the list of all files needs to be rename and new.txt with the new names. For example, old.txt

23654.jpg
hello world.doc
ok, it's done.docx

new.txt

2018.jpg
old.doc
...

I wanted to read line by line those files and use them in arguments with the command mv. I can do it with one file (while read line) but I don't know how to manage the second file...

In conclusion, I want to use 2 files as sources of arguments for another bash command.

Any ideas?

Thank you


Solution

  • You can use another read with a different FD:

    while IFS= read -r old_name && IFS= read -r new_name <&3; do
        mv -- "$old_name" "$new_name"
    done <old.txt 3<new.txt
    

    Or using paste and GNU xargs (for the -d option):

    paste -d'\n' {old,new}.txt | xargs -d'\n' -n2 mv --