Search code examples
bashsedgreppipelinefind-replace

Find&Replace a quoted string with grep | sed


I need to remove in a text file all quotation marks which enclosure strings that always begins with the same, but ends in a different way:

'something.with.quotation.123' must be something.with.quotation.123
'something.with.quotation.456' must be something.with.quotation.456

but quotated strings that doesn't begin with this should not be changed.

I've been working with a grep that finds & prints the quotated strings:

grep -o "something\.with\.quotation\.[^']*" file.txt

Now I need to pass the results to sed through a pipeline, but it doesn't work:

grep -o "something\.with\.quotation\.[^']*" file.txt | sed -i "s/'$'/$/g" file.txt

I've been trying with other options ("s/\'$\'/$/g", "s/'\\$'/\\$/g",...) and googling a lot, but no way.

Can you point me to the correct way to get a result from a pipeline in sed?


Solution

  • You don't need grep here. Just use sed like this:

    cat file
    'something.with.quotation.123'
    'something.with.quotation.456'
    'foo bar'
    
    sed -E "s/'(something\.with\.quotation\.[^']*)'/\1/g" file
    something.with.quotation.123
    something.with.quotation.456
    'foo bar'