Bash – How to do more than one substring replace at once in bash

bashreplaceshell-script

I have a directory contains image files that are to be echoed in bash. While echoing, I want to replace both file name and extension in single line command.

Example files:

images/file_name_1.jpg
images/file_name_2.jpg

Normally, I can do single replacement like this:

for i in images/*; do echo ${i/file/image}; done

And the output becomes like:

images/image_name_1.jpg
images/image_name_2.jpg

How can I keep it in for loop and replace the "jpg" string to "png" also? It's just an instance, I could replace the dot to comma etc.

When I try this:

for i in images/*; do echo ${{i/jpg/png}/file/image}; done

It doesn't work. I coulnd't find any other solution or idea. Is this possible -if so, how?

Best Answer

The simple approach would be to assign the result to a variable, then work with that variable. Example:

for filename in images/*
do
    echo "filename is now $filename"
    filename=${filename/jpg/png}; echo "filename is now $filename"
    filename=${filename/file/image}; echo "filename is now $filename"
    echo "final filename is ${filename}"
done
Related Question