Lorr
Lorr

Reputation: 361

Sed get text from start until after the match ends

I want to get out the text from start to the match ends. For example:

Hello my name is F!Hello my name is Tom. No my name is Phil.

Show everything to "!" so I'm only getting out "Hello my name is F" but wat I want is "Hello my name is F!"

Upvotes: 0

Views: 193

Answers (3)

shellter
shellter

Reputation: 37288

Or you can substitute everything you don't want with "!", i.e.

  echo "Hello my name is F!Hello my name is Tom. No my name is Phil." \
  | sed 's/!.*$/!/'

output

Hello my name is F!

IHTH

Upvotes: 1

0xAX
0xAX

Reputation: 21817

You can use \1 to keep part of a pattern that you are interested in:

$ echo "Hello my name is F! no no" | sed -e 's/\(\!\).*/\1/'
Hello my name is F!

If you want to use ![any symbol right after !] like in our example, you will get escaped !:

$ echo -e "Hello my name is F\!Hello my name is Tom. No my name is Phil." | sed -e 's/\(\!\).*/\1/g'
Hello my name is F\!

To prevent this you can feed the result to yet another sed script:

~$ echo -e "Hello my name is F\!Hello my name is Tom. No my name is Phil." | sed -e 's/\(\!\).*/\1/g' | sed -e 's/\\//g'
Hello my name is F!

Upvotes: 0

Andrew Kay
Andrew Kay

Reputation: 274

If your input file is "test", this will print out each line of test up to and including the "!"

sed -e 's/\(.*!\).*/\1/' test

Upvotes: 0

Related Questions