You are here

File renaming using sed and xargs: Prefixing all filenames with a 0 from the commandline

Submitted by Druss on Tue, 2011-01-25 00:56

Earlier today, I wanted to prefix a number of image files on a server with a 0. If this was on my desktop, I would have simply used a graphical tool such as the excellent M├ętamorphose. However, in this case, only a command-line was available. While Google threw up a number of bash scripts, I was curious to see if this could be done in a cleaner and more concise manner. Following the excellent reference to sed and more Google magicking, I arrived at
ls | sed -e 'p;s/^/0/' | xargs -n2 mv

Breaking the above commands down:

  1. The ls command simply lists the contents of the directory in a bare format.
  2. The contents of the list command are piped into the sed command.
  3. First, sed uses the p; command to print the input filename as is. This is because we will be using this filename as the from argument for the mv command later on.
  4. Next, sed uses a regular expression substitution to insert a 0 at the start of each line. This will effectively become the to argument for the mv command.
  5. The output of sed is now piped into the xargs command.
  6. xargs specifies that we are providing two arguments using the -n2 switch. The two arguments in question are the from and to filenames provided by sed.
  7. These two arguments are then passed to the mv which will now rename the files accordingly.

Seeing as to how such commands are commonly used for batch operations, it is highly recommended that you test things out on some test input beforehand. It is also worthwhile testing the output of each section of the command to ensure that it is performing as expected. The xargs switches -pt can be useful while doing this as they enable prompting as well as verbosity.

I hope all that made sense :)