Using sed + xargs to rename multiple files
Post first published in nixtip
Lets say that whe have a bunch of
txt files and we need to rename to
We can use
ls combined with
xargs to achieve our goal.
How it works:
ls output is piped to
sed , then we use the
p flag to print the argument without modifications, in other words, the original name of the file.
The next step is use the substitute command to change file extension.
NOTE: We’re using single quotes to enclose literal strings (the dot is a metacharacter if using double quotes scape it with a
The result is a combined output that consist of a sequence of
Finally we pipe the resulting feed through
xargs to get the effective rename of the files.
PD: Alternative path to take care of spaces in the file names:
Here’s the CMD:
From the man page:
comments powered by Disqus
xargs combines the fixed initial-arguments with arguments read from standard input to execute the specified command one or more times. The number of arguments read for each command invocation and the manner in which they are combined are determined by the options specified. [/sourcecode]
The n parameter
-n number Execute command using as many standard input arguments as possible, up to number arguments maximum. Fewer arguments are used if their total size is greater than size bytes, and for the last invocation if there are fewer than number arguments remaining. If option -x is also coded, each number arguments must fit in the size[/sourcecode]
The -n2 flag force xargs to take 2 arguments from the piped output each time and parses it to the mv command to get the job done.