0

I want to compress image files and wrote the following bash script:

for i in *.png; do convert $i -quality 100% $i-comp.jpeg; done;

When I run it I get filenames like 48.png-comp.jpeg. I only want to have like 48-comp.jpeg, so basically removing the .png part of the filename.

I tried using this ${$i/.png/}, which gives me an error message.

Any suggestions how to do this?

Carol.Kar
  • 4,581
  • 36
  • 131
  • 264
  • 1
    `${$i/.png/}` is almost correct, just remove the second `$` since it's not used inside a parameter expansion: `${i/.png/}` – heittpr Mar 06 '22 at 13:26
  • @heitor I modified the script like that: `for i in *.png; do ${i/.png/}; convert $i -quality 88% $i-comp.jpeg; echo $i; done;` However, now the compression does not take place. I guess my current script is wrong. Any suggestion what is wrong? – Carol.Kar Mar 06 '22 at 13:28
  • 1
    You need to pass the new filename as an argument to `convert`: `convert "$i" -quality 88% "${i/.png}-comp.jpeg"` – heittpr Mar 06 '22 at 13:32

2 Answers2

1

You could use parameter expansion to strip the png extension for the output file name:

for i in *.png; do convert $i -quality 100% ${i%.png}-comp.jpeg; done
Cole Tierney
  • 9,571
  • 1
  • 27
  • 35
1

${$i/.png/} is almost correct, but the second $ is not needed inside a Parameter Expansion.

#!/bin/bash

for i in *.png; do
  convert "$i" -quality 88% "${i/.png/}-comp.jpeg"
done

Note: ${i%.png} is commonly more used to remove a file extension than ${i/.png/}, but both should produce the same output.

heittpr
  • 591
  • 4
  • 9