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:
Note a blank search pattern (as in
s///p
) reuses the last pattern.Alternatively:
(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 outputtingxxx
, then you can just do:(or remove the
p
flag to the firsts
command in the other commands above).