user1318369 user1318369 - 1 year ago 97
Bash Question

String replace in unix

I am to remove some text after a number for example: 1.2.0_testing. I just want the number part which is 1.2.0. SO anything after the underscore needs to be removed.
Below is the code I am using:

echo $str | sed 's/_*//'

However the wildcard doesn't seem to work and I still get the full string. Can someone please help me.


Answer Source

No need for expensive forks to sed, awk, or - gasp! - perl. The shell can do this nicely:

$ str=1.2.0_testing
$ echo ${str%%_*}     # Remove longest part from the right matching _*

Learn all there is about built-in string manipulation with %, %%, #, ## in your fine shell manual. These remove from the right (percent) or left (hash) the shortest (single) or longest (double) match.