PKR PKR - 5 months ago 12
Bash Question

ksh shell script to find first occurence of _ in string and remove everything until that

Im New To Shell Scripting.Using KSH Shell. Could you please help me in this.

My string is like errorfile101_ApplicationData_2_333.txt. I want to remove everything until the first occurence of _.

My output should be ApplicationData_2_333.txt


This is an easy one, assuming you can assign your string to a variable, i.e.

echo ${str#*_}



The # operator in ${str#*_} means remove the following pattern from the left of the variable's value.

There is also ##, which removes the longest match from the left, which would give you


There are also similar removal operators for working from the right side of the string, % and a longest match (from right) with %%.

All versions of ksh (and bash, and other shells) support these operators. (sorry if this is the wrong term).

Versions of ksh93 and greater (bash, zsh and probably others) also support a sed like pattern match/sub value like

echo ${str/*_/xx}
#----------> pattern to match



which means that / works like sed matching the longest possible string.