Search code examples
stringubuntusedreplaceescaping

Search and replace not working in sed for string containing space and special character


I want to prefix the line containing the string echo '"xxx.yyy" with "# " (hash+space) in file.txt using sed in Linux.

Output should look like this:

# echo '"xxx.yyy"

I tried this:

find file.txt -type f -exec sed -i 's|"echo '"xxx.yyy""|"# echo '"xxx.yyy""|g' {} \;

But I am getting the error:

sed: -e expression #1, char 23: unterminated `s' command

Should I escape any character here? What am I doing wrong here?


Solution

  • I will show the sed commands without -i. Add -i when it works like you want.
    When you are not sure how much quotes you have, you can try

    sed 's/echo [^[:alnum:]]*xxx.yyy[^[:alnum:]]/# &/' file.txt
    

    or when you are already happy when a line has both echo and xxx.yyy:

    sed 's/echo.*xxx.yyy/# &/' file.txt
    

    In both commands, the & stands for the part that is matched.