简体   繁体   中英

Recursively rename .jpg files in all subdirectories

I am on a Linux system and I am trying to rename all .jpg files in many subdirectories to sequential filenames, so all the jpeg files in each subdirectory are renamed 0001.jpg, 0002.jpg, etc. I have a 'rename' command that works in a single directory:

rename -n 's/.*/sprintf("%04d",$::iter++ +1).".jpg"/e' *.jpg

I am trying to use it like this:

for i in ls -D; do rename -n 's/.*/sprintf("%04d",$::iter++ +1).".jpg"/e' *.jpg; done

but for output I get this:

*.jpg renamed as 0001.jpg

for each subdirectory. What am I doing wrong?

You need to put the command in backticks (or use the $( ... ) bash syntax) in order to iterate over its output. Also use the $i variable together with the *.jpg file name pattern, eg

for i in `ls -D`
do
    rename -n 's/.*/sprintf("%04d",$::iter++ +1).".jpg"/e' $i/*.jpg
done

however, for this scenario you want to iterate over all the subdirectories, and you are better of using the find command:

for i in `find . -type d`; do rename ...

It seems to me you've forgot to change a current working directory so it should looks like

for i in *; do
  [ -d "$i" ] || continue
  pushd "$i"
    # rename is here 
  popd
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM