简体   繁体   中英

Renaming files in Shell script for loop

I run OS X and have multiple photos and started naming them xyz-100.jpg , xyz-101.jpg , xyz-102.jpg up to xyz-402.jpg and now want to rename them by basically reducing the number by 99, making it xyz-1.jpg , xyz-2.jpg up to xyz-303.jpg .

I know I can use the mv command for that, but I don't seem to be able to implement a variable into the filename, such as xyz-$reduced.jpg . How can I properly do that?

something like this should work. but i'm not sure how you're obtaining the number of files. you could also cat the output of another file that list filenames to the same effect as this. but this should get you started

num_array=(1 2 3 4 5)

for i in "${!num_array[@]}"; do
       mv -i ./"myfile_${i}.jpg" /somehwere_else
done

I strongly recommend you move them to another directory, since otherwise you run the risk of confusion if something bad happens midway through. So try:

mkdir tmp
for ((n=100; n<=402; n++)); do 
  ln xyz-$n.jpg tmp/xyz-$((n-99)).jpg
done

That should give you the files you want inside tmp/ . Then you can move that directory where you'd like and remove the old files. If you're not familiar with ln , think of it as half of a mv . Basically mv foo bar is the same as ln foo bar; rm foo ln foo bar; rm foo . By linking the newly named files in a subdirectory, you won't have any conflicts trying to figure out if file 150 is really 150 or if it is the renamed 249. Also, instead of iterating through the existing files and trying to parse the number, just use jot to generate the names that you know you want.

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