Sarah92
Sarah92

Reputation: 671

sed script to remove everything in brackets over multiple lines

I am trying to use sed script to remove the content of an array in a file. I have tried to delete the content to only leave the brackets (). However I can't get the sed script to work over multiple lines.

I am trying to change the current state of the file:

LIST = ( "content"
         "content1"
         "content3")

to this:

LIST = ()

However the sed script I am using only changes the file to this:

LIST = ()
     "content"
     "content1"
     "content2"

sed -e 's/LIST=\([^)]*\)/LIST=() /g' filename

I should also mention there are other sets of brackets in the file which I don't want affected.

e.g

LISTNUMBER2("CONTENT")  

should not be emptied.

Upvotes: 1

Views: 2517

Answers (2)

William
William

Reputation: 4925

Another sed solution:

sed '/LIST = (/{:next;/)/{s/(.*)/()/;b;};N;b next;}'

Here's a version that would not change any block containing a certain string ("keepme" in this example, but could be anything):

sed '/LIST = (/{:next;/)/{/keepme/b;s/(.*)/()/;b;};N;b next;}'

Since this does the keepme test after it finds the closing parenthesis that tag can be anywhere in the block.

Upvotes: 1

Kent
Kent

Reputation: 195029

this sed one-liner works for your example:

sed -n '1!H;1h;${x;s/(.*)/()/;p}'

test:

kent$  echo 'LIST = ( "content"
         "content1"
         "content3")'|sed -n '1!H;1h;${x;s/(.*)/()/;p}'
LIST = ()

if you could use awk, this one-liner works for your example too:

awk -v RS="" '{sub(/\(.*\)/,"()")}1' 

test:

kent$  echo 'LIST = ( "content"
         "content1"
         "content3")'|awk -v RS="" '{sub(/\(.*\)/,"()")}1'                                                                                                                  
LIST = ()

EDIT for OP's comment

multi brackets situation:

awk

 awk -v RS="\0" -v ORS="" '{gsub(/LIST\s*=\s*\([^)]*\)/,"LIST = ()")}1' file

test:

kent$  cat file
LISTKEEP2("CONTENT")  
LIST = ( "content"
         "content1"
         "content3")
LISTNUMBER2("CONTENT")  

kent$  awk -v RS="\0" -v ORS="" '{gsub(/LIST\s*=\s*\([^)]*\)/,"LIST = ()")}1' file
LISTKEEP2("CONTENT")  
LIST = ()
LISTNUMBER2("CONTENT") 

sed:

 sed -nr '1!H;1h;${x;s/(LIST\s*=\s*\()[^)]*\)/\1)/;p}' file

kent$  sed -nr '1!H;1h;${x;s/(LIST\s*=\s*\()[^)]*\)/\1)/;p}' file
LISTKEEP2("CONTENT")  
LIST = ()
LISTNUMBER2("CONTENT")

Upvotes: 1

Related Questions