views:

482

answers:

1

I'm reading from a line that's about 500 characters. How can I get sed to, instead of replacing that string with something, replace the rest of the line with something? In short, I want to remove all the text around a specified string. Deleting columns with awk won't work, because there is an indeterminate amount of characters before and after the matched string. Any ideas?

+5  A: 

Try using back references:

sed 's/.*\(searchstring\).*/___\1___/'

The .*'s around the search string will match everything but the string, and the parentheses tell sed to remember what it matched. You can refer to the first matched string with \1.

Here's an example (replacing everything but 'bar baz'):

$ echo "foo bar baz qux" | sed 's/.*\(bar baz\).*/___\1___/'
___bar baz___

You can replace 'bar baz' with whatever pattern you like in the above; I just used a basic string for simplicity.

tgamblin