1

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!

1
  • That's not a wildcard, it's a regular expression! Commented May 5, 2016 at 11:19

2 Answers 2

4

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 _.

Sign up to request clarification or add additional context in comments.

1 Comment

Forking sed to remove a few characters from the end of a shell string is an anti-pattern that should not be proliferated.
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.