Download and view my resume (PDF)

Thursday, September 9, 2010

Rename Files In Unix

This is a one-liner for renaming a lot of files in a directory using Unix tools.

for file in `find . -type f -print`; do cp $file newdir/`basename $file|sed s/origpart/replacepart/`; done
  1. `find . -type f -print` prints a list of all the files in the current directory.
    • find is a utility for finding files
    • The period indicates that we should find files in the current directory
    • -type f means find only regular files (not directories)
    • -print means print the list in a normal way that can be input to other commands
    • The backticks mean that the find command is executed, and the output saved for use in the larger command

  2. for file in does a command for each of a list of things, and each time puts the thing into a variable called "file"
    • the for command is terminated by a semicolon, then followed by a do command, then a done command

  3. `basename $file|sed s/origpart/replacepart/` takes a full file name and strips off its directory and extension, then replaces "origpart" with "replacepart"
    • basename $file takes the file name (given to us by the for command) and removes the preceding directory, if any, and the filename extension, if any.
    • sed means "stream editor" and it reads in some text and edits it. In this case we are reading in the filename, and substituting "replacepart" for "origpart". s/x/y/ means to replace x with y.
    • So the output of this part of the one-liner is a modified filename.
    • Again, the backticks mean to take the output of this command and save it for use in the larger command

  4. do cp $file newdir/ copies files into a new directory
    • do is required because we are following a for command.
    • cp means "copy", one of the most standard Unix commands.
    • cp a b means to copy file a to b, and b can be in a new directory. In our case, we copy the original file into the "newdir" directory, and the new file name comes from the `basename $file|sed s/origpart/replacepart/` part
    • Again, a do command is terminated by a semicolon

  5. done represents the end of the previous for command.
So you can see that this command creates a list of all the files in the current directory, loops over that list calling each item in the list "$file", modifies the filename by replacing one part of it with something new, then copies the file into a new file in a new location.

No comments:

Post a Comment