Celeb Glow
news | March 14, 2026

Replace string between 2 wildcard characters in a variable value using bash scripting

I have a variable value "Cash_20200413_US_02.dat" and I want to rename it as "Cash_20200413_US_*.dat".

So basically I want to find : a) the last occurence of string "_" and b) string "." and then replace the value between these two strings to "*"

Input="Cash_20200413_US_02.dat"

Output="Cash_20200413_US_*.dat"

1 Answer

Given

Input="Cash_20200413_US_02.dat"

you can get the substring up to the last underscore (excluded) with:

echo "${Input%_*}"

and the substring from the last dot (excluded) with:

echo "${Input/*.}"

Combining both, with the requested string in between:

Output="${Input%_*}_*.${Input/*.}"
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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