jakesandlund
jakesandlund

Reputation: 401

Sed replace entire line with replacement

I posted this question on superuser a bit ago, but I haven't gotten an answer I like. Here it is, slightly modified.

I was hoping for a way to make sed replace the entire line with the replacement (rather than just the match) so I could do something like this:

sed -e "/$some_complex_regex_with_a_backref/\1/"

and have it only print the back-reference.

From this question, it seems like the way to do it is mess around with the regex to match the entire line, or use some other tool (like perl). Simply changing the regex to .*regex.* doesn't always work (as mentioned in that question). For example:

$ echo $regex
\([:alpha:]*\)day

$ echo "$phrase"
it is Saturday tomorrow
Warm outside...

$ echo "$phrase" | sed "s/$regex/\1/"
it is Satur tomorrow
Warm outside...

$ echo "$phrase" | sed "s/.*$regex.*/\1/"

Warm outside...

$ # what I'd like to have happen
$ echo "$phrase" | [[[some command or string of commands]]]
Satur
Warm outside...

I'm looking for the most concise way to replace the entire line (not just the matching part) assuming the following:

What I thought of was the following (but it's ugly, so I'd like to know if there is something better):

$ sentinel=XXX
$ echo "$phrase" | sed "s/$regex/$sentinel\1$sentinel/" |
> sed "s/^.*$sentinel\(.*\)$sentinel.*$/\1/"

Upvotes: 1

Views: 1385

Answers (1)

potong
potong

Reputation: 58351

This might work for you:

sed '/'"$regex"'/!b;s//\n\1\n/;s/.*\n\(.*\)\n.*/\1/' file

Upvotes: 2

Related Questions