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:
lscommand simply lists the contents of the directory in a bare format.
- The contents of the list command are piped into 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
mvcommand later on.
seduses a regular expression substitution to insert a 0 at the start of each line. This will effectively become the to argument for the
- The output of
sedis now piped into the
xargsspecifies that we are providing two arguments using the
-n2switch. The two arguments in question are the from and to filenames provided by
- These two arguments are then passed to the
mvwhich 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 :)