Main menu

You are here

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

Tue, 2011-01-25 00:56 — Druss

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 atls | sed -e 'p;s/^/0/' | xargs -n2 mv

Breaking the above commands down:

The ls command simply lists the contents of the directory in a bare format.

The contents of the list command are piped into the sed command.

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.

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.

The output of sed is now piped into the xargs command.

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.

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.