Search code examples
bashrenamefile-rename

Rename files reading old file name and new file name from a txt file (bash)


I need to rename a bunch of files in a directory:

2016001.fas
2016002.fas
2016003.fas
...

Reading through a .txt that has the actual and the new filename tab separated:

2016001 L.innocua001
2016002 L.innocua002
2016003 L.monocytogenes001
...

Maybe using a one line for loop or a pipe in bash.

As a note, I can also have the list with actual and new filename in .csv or comma separated .txt format if needed. I appreciate the help given.


Solution

  • xargs -a renames.txt -n 2 sh -c 'echo mv -- "$1.fas" "$2.fas"' _
    
    • xargs -a renames.txt: process content of the renames.txt as arguments to a command.
    • -n 2: pick 2 arguments at a time.
    • sh -c: command is to run an inline shell
    • The inline shell 'echo mv -- "$1.fas" "$2.fas"': Performs the actual rename using arguments 1 and 2 provided by xargs.
    # remove echo when output matches the intent
    echo mv -- "$1.fas" "$2.fas"
    

    Method using a shell only to read renames.txt and execute the renames:

    while read -r a b; do
      # Remove echo if satisfied by the output
      echo mv -- "$a.fas" "$b.fas"
    done <renames.txt
    

    Alternate method with awk to transform the renames.txt file into a shell script with the rename commands:

    awk '{print "mv -- "$1".fas "$2".fas"}' renames.txt
    

    Once satisfied by the output of awk above; save to a shell script file, or pipe directly to sh.