Sed – perform multiple substitutions on a line found by pattern search

sed

I have a file which contains a like like this:

name=MOD0

and a lot of extra lines which I'm not interested in.
I need to transform this line into this:

[MOD0]

and drop all other lines from the file.
The MOD0 part is not predictable, so I need to match the line by the ^name= pattern. I can perform one substitution (remove the "name="), but how do I tell sed to perform another operation (surround the line with brackets), still on the same matched line? The following command surrounds every line with brackets:

sed -n -e '/^name=/ s/^name=//p; s/^.*$/\[&\]/p'

Best Answer

Use braces:

sed -n '
   /^name=/ {
     s///p
     s/.*/[&]/p
   }'

Note a blank search pattern (as in s///p) reuses the last pattern.

Alternatively:

 sed '/^name=/!d;s///p;s/.*/[&]/'

(that is delete the lines that don't start with name= and then process the other ones).

If you just want to replace the name=xxx with [xxx] without also outputting xxx, then you can just do:

sed -n 's/^name=\(.*\)/[\1]/p'

(or remove the p flag to the first s command in the other commands above).

Related Question