Wednesday, April 13, 2022

[SOLVED] Get basename of files in folder

Issue

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?


Solution

${$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.



Answered By - heitor
Answer Checked By - Senaida (WPSolving Volunteer)