3

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'
5

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).

  • This prints two lines for each match. You have to remove the first 'p' action in the first two solutions. – daniel kullmann Mar 19 '15 at 9:42
  • Thanks! :) I managed to find out that multiple commands can be combined into blocks with braces, but the last command in your answer is simpler a does exactly what I need. – myxal Mar 19 '15 at 9:43
  • @danielkullmann, that was my assumption on what the OP wanted to do based on his example. I clarify that in the second part of the answer which is why I reversed your edit. – Stéphane Chazelas Mar 19 '15 at 9:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.