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:
- 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 thep;
command to print the input filename as is. This is because we will be using this filename as the from argument for themv
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 themv
command. - The output of
sed
is now piped into thexargs
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 bysed
.- 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 :)
- Log in to post comments