Search code examples
linuxbashsedrhel

Unterminated 's' command with 's/([\^][^])//g'


I am trying to find any caret (^) characters in my file, and delete them and the subsequent character whenever they exist. I am running this in bash.

Any time I try and run the sed to do so:

sed -i 's/([\^][^])//g' myfile.txt

I get the below error:

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

Any ideas?


Solution

  • The expression [^] is unfinished because sed is using the ] following the carat ^ as a negative list of characters, there is a missing ] ([^]]) needed. But that will match a closing ], nothing you want (I believe).

    What I believe you intend is to match a carat: \^. But what you wrote ([\^]) will not match a carat either. That will match either a backslash \ or a carat ^:

    $  echo 'abc\def^ghij'
    abc\def^ghij
    
    $ echo 'abc\def^ghij' | sed 's/[\^]//g'
    abcdefghij
    

    But even that is not what you have written:

    find any carat (^) ... and delete them and the subsequent character whenever they exist

    If the intended subsequent character is any character, use: \^.
    If the subsequent character is any character that is not a carat, use: \^[^\^]
    Or simply: \^[^^]

    $ echo 'ab\cd^^ef^gh' | sed 's/\^[^^]//g'
    ab\cd^fh
    

    That is:

    sed -i 's/\^[^^]//g' infile
    

    Is that what you are looking for?