Xargs file rename

Let's say you want to rename files that match a certain pattern, and are spread out amongst many other files in a folder tree. Using pipes in a terminal, this can be achieved easily.

The biggest problem is that you want to give mv two dynamic arguments, with the second one calculated from the first one. Pipes only forward a single stream. However, we can use the p command in sed, and a semicolon separator, to output two lines for every single input line: one original line and one line calculated from the original.

Another problem is spaces in filenames. Xargs will normally break at space, tab or newline. Using the argument -0 will tell xargs to only break at NUL, and treat spaces as normal characters. Using tr we can convert newline characters to NUL, which is great since find uses newline characters to separate filenames.

Putting it all together, this expression will find all files that have names ending with sv-SE.json and change the filename to instead end with en-GB.json:

find . -name "*sv-SE.json" | sed "p;s/sv-SE\.json$/en-GB\.json/" | tr "\\n" "\\0" | xargs -n 2 -0 mv


Appreciate you sharing, great forum.Much thanks again. Tron


Add new comment

By submitting this form, you accept the Mollom privacy policy.