Taztingo Taztingo - 4 months ago 16
Bash Question

Replace text within searched text using sed and awk?

I have some text in a text file that looks like this:

BLAHBLAHBLAH RANDOM DATA
data = [
#'oink',
#'bigger oink',
#'stronger oink',
#'strongest oink',
#'beyond godlike oink'
]
BLAHAHAHA RANDOM LASDKFJS DATA


I'm trying to remove all the # that are within the data array. My first attempt I did this:

sed -i "s/# '/'/g" file


This worked great however, it searched outside of the data[] scope.

I then tried to combine awk with sed

awk '/data = \[/,/\]/' file | sed -i "s/# '/'/g"


However I was unable to do that because sed is not getting an input file.

How can I combine these, or how can I do it with one command?

Answer

Keep it simple:

awk '/data = \[/{f=1} f{sub(/#/,"")} /\]/{f=0} 1' file

For example, borrowing @anubhava's input and massaging to include a line with a # inside the quoted text:

$ cat file
# text
BLAHBLAHBLAH RANDOM DATA
    data = [
            #'oink',
            #'bigger oink',
            #'stronger oink',
            #'mother #$^*@ oink',
            #'beyond godlike oink'
        ]
    BLAHAHAHA RANDOM LASDKFJS DATA

            #'stronger oink',
            #'strongest oink',

$ awk '/data = \[/{f=1} f{sub(/#/,"")} /\]/{f=0} 1' file
# text
BLAHBLAHBLAH RANDOM DATA
    data = [
            'oink',
            'bigger oink',
            'stronger oink',
            'mother #$^*@ oink',
            'beyond godlike oink'
        ]
    BLAHAHAHA RANDOM LASDKFJS DATA

            #'stronger oink',
            #'strongest oink',

The above will work with any awk on any OS.