1

Currently I have the following bash script that does a for loop in the directory:

for filename in *-example99.jpg
do
   width=$(identify -format "%w" "$filename")
   myVar="newName$width"
   new=$(echo $filename | sed -e 's/\.jpg$/"$myVar".jpg/')
   echo "$filename" "$new"
   mv "$filename" "$new"
done

actually, I want to rename the file from:

myfilename-example99.jpg

to:

myfilename-newName.jpg

How can I achieve this?

5
  • See: unix.stackexchange.com/search?q=batch+rename or the list of questions on the right side bar
    – ilkkachu
    Dec 11 '17 at 16:21
  • Your previous question investigated the image dimensions; is that no longer involved?
    – Jeff Schaller
    Dec 11 '17 at 16:22
  • Note that “newName” is a static string; you’d be renaming all the files to one...
    – Jeff Schaller
    Dec 11 '17 at 16:23
  • @JeffSchaller i will be getting some part of the custom variable from the width of the image. Dec 11 '17 at 16:25
  • Apart from the quoting being off (esp. with the sed), doesn't the renaming and the loop look fine?
    – ilkkachu
    Dec 11 '17 at 16:26
3

You don't need to call out to sed: bash parameter substitution can handle this task. Try this:

suffix="-example99.jpg"
for filename in *"$suffix"        # wildcard * must remain unquoted
do
   width=$(identify -format "%w" "$filename")
   new="${filename%$suffix}-newName${width}.jpg"
   echo mv "$filename" "$new"
done

The ${filename%$suffix} removes the suffix from the end of the string. See https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion

0

Simply with prename (Perl rename):

myVar="newName"
prename 's/-[^-.]+(\.jpg)$/-'"$myVar"'$1/' *-example99.jpg
1
  • how can i specifiy the file that is being looped? cuz i am inside a for loop Dec 11 '17 at 16:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.