Search code examples
bashfilefile-rename

Renaming multiple files using list of files


In bash how would I rename multiple files using names from a text file, I have a directory with multiple .mp3 files: 1.mp3. 2.mp3, 3.mp3, 4.mp3 etc... and a text file: names.txt with: song1.mp3 song2.mp3 song3.mp3 etc..

first line in the text file will correspond to the first line of the file , second line to the second line etc. I have found a few ways to do it in python, but would like to learn how to accomplish this in bash, thanks in advance!


Solution

  • If the files in your directory have names, like 1.mp3, that contain no tabs or newlines, then the following will work:

    printf "%s\n" *.mp3 | paste - file | while IFS=$'\t' read -r old new; do mv "$old" "$new"; done
    

    This will work even in the new file names contain blanks, like Joe's "favorite" song.mp3.

    How it works

    The printf statement writes each mp3 file name, one per line:

    $ printf "%s\n" *.mp3
    1.mp3
    2.mp3
    3.mp3
    

    The paste command combines the old file names and the new, separating them by a tab:

    $ printf "%s\n" *.mp3 | paste - file2
    1.mp3   song1.mp3
    2.mp3   song2.mp3
    3.mp3   song3.mp3
    

    The read command, IFS=$'\t' read -r old new, reads the old and new file names into the shell variables old and new.

    The mv command, mv "$old" "$new", renames the files.

    Multiple line version

    If you like your code spread over multiple lines:

    printf "%s\n" *.mp3 | paste - file | while IFS=$'\t' read -r old new
    do
        mv "$old" "$new"
    done