Wednesday, September 5, 2012

Bash script - Delete characters before or after a pettern from string

I have this string:

MyString="This is a Test. Isn't it? Yes, it is."

I want to delete all characters after "?":

echo $MyString | sed -e 's/?.*//g'

the result is: This is a Test. Isn't it

now I want to delete all characters before "a":

echo $MyString | sed -e 's/.*a//g'

Resut: Test. Isn't it? Yes, it is.




2 comments:

Anonymous said...

you said that you were deleting all of the characters after the "?", but you deleted all of the characters after the "?" AND the "?". How do you delete everything AFTER the "?" but NOT the "?"

Anonymous said...

Just to answer this question,just add the "?" into the section of the sed commeand that is going to replace the text. which before was nothing now would be a "?"

sed -e 's/?.*/?/g'