Home > Software design >  Renaming bunch of files with xargs
Renaming bunch of files with xargs

Time:06-15

I've been trying to rename a bunch of files in a proper order using xargs but to no avail. While digging around on piles of similar question, I found answers with the use of sed alongside xargs. Novice me wants to avoid the use of sed. I presume there must be some easier way around.

To be more specific, I've got some files as follows:

Abc.jpg
Def.jpg
Ghi.jpg
Jkl.jpg

and I want these to be renamed in an ordered way, like:

Something1.jpg
Something2.jpg
Something3.jpg
Something4.jpg

Could xargs command along with seq achieve this? If so, how do I implement it?

CodePudding user response:

I don't know why anyone would try to engage sed for this. Probably not xargs or seq, either. Here's a pure-Bash one-liner:

(x=1; for f in *.jpg; do mv "$f" "Something$((x  )).jpg"; done)

At its core, that's a for loop over the files you want to rename, performing a mv command on each one. The files to operate on are expressed via a single glob expression, but you could also name them individually, use multiple globs, or use one of a variety of other techniques. Variable x is used as a simple counter, initialized to 1 before entering the loop. $((x )) expands to the current value of x, with the side effect of incrementing x by 1. The whole thing is wrapped in parentheses to run it in a subshell, so that nothing in it affects the host shell environment. (In this case, that means it does not create or modify any variable x in the invoking shell.)

If you were putting that in a script instead of typing it on the command line then it would be more readable to split it over several lines:

(
  x=1
  for f in *.jpg; do
    mv "$f" "Something$((x  )).jpg"
  done
)

You can type it that way, too, if you wish.

CodePudding user response:

This is an example of how to find, number and rename jpgs. Regardless of how you use the find (what options you need. recursive, mindepth, maxdepth, regex, ...).

You can add numbers to find ouput with nl and use number and file as 2 arguments for xargs $1, $2

$ find . -type f -name "*.jpg" |nl| xargs -n 2 bash -c 'echo mv "$2" Something"$1".jpg' argv0

the echo echo mv ... will show this

mv ./Jkl.jpg Something1.jpg
mv ./Abc.jpg Something2.jpg
mv ./Def.jpg Something3.jpg

Using sort and testing the number of arguments

$ find . -type f -name "*.jpg" |sort|nl| xargs -n 2 bash -c '[ "$#" -eq 2 ] && echo mv "$2" Something"$1".jpg' argv0
mv ./Abc.jpg Something1.jpg
mv ./Def.jpg Something2.jpg
mv ./Jkl.jpg Something3.jpg
  • Related