user1318369
user1318369

Reputation: 715

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.

Thanks!

Upvotes: 1

Views: 63

Answers (2)

Vadiraja K
Vadiraja K

Reputation: 839

Try this,

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

. - Matches any single character.

* - Matches zero or more occurrences of the previous character

So, _.* would represent 0 or more characters following _.

Upvotes: 4

Jens
Jens

Reputation: 72639

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 _*
1.2.0

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.

Upvotes: 3

Related Questions