I need to parse a text file and replace a certain portion of it. I believe sed is the way to do it but not sure how to handle multiple lines with it

The pattern I am looking is

set cells { \  
cell1 \  
cell2 \  
cell3 \  

and I want to replace it with the contents of a variable.

Something like the following should do the trick, but it doesn't work on multiple lines. Any ideas?

sed "s/set cells {.*}/set cells {$cell_variable}/" file

  • If your command is working then you are just missing the g. sed "s/set cells {.*}/set cells {$cell_variable}/g" file – Mongrel Mar 22 '16 at 12:31

If it must be sed:

sed -i.bak ':a;N;$!ba;s/set cells {.*}/set cells{\n'$cell_variable'\n}/g' file
  • -i.bak creates a backup of the original file before editing inline.
  • :a create label a to jump back.
  • N append the next line of input into the pattern space.
  • $! if it's not the last line...
    • ba jump back to label a
  • s///g search and replace the patterns

A simpler solution with perl:

perl -0777 -i.bak -pe "s/set cells \{.*\}/set cells{\n$cell_variable\n}/igs" file
  • -0777 causes perl to slurp files whole.
  • -i.bak creates a backup of the original file before editing inline.

I wanted to avoid perl as an extra tool to use. I could not make chaos solution to work for some reason, but reading a bit on sed I came up with an alternative which is here

sed "/set cells/!b; :Loop; N; /}/!b Loop; s/.*/set cells {$cell_def}/" -i file
  • /set cells/!b : Look for set cells, if not found go to next line
  • :Loop : label used to merge multiple lines
  • N : append the next line
  • /}/!b Loop : Look for an }, if not found go back to label Loop. In practice the loop reads a new line until the } is found
  • s/.*/set cells {$cell_def}/ : replace everything with my own set cells command. At this point the whole statement including the {.*} should be read.

Thank you for the help everybody

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.