I'm having some trouble when attempting to remove a string between the string end and the character ;. At the moment it looks like I'm also picking up the string if on other lines as that string is also between end and ;. I've been attempting to omit the if string from the command but I don't seem to be having much look using the below sed command as I receive a error. The string triggername is what needs to be removed, but it's not consistently named that.

Example File Before:

end if;
    end triggername ;

Example File Expected:

end if;

The command I've been attempting to use is:

sed -i -e '/if/! s/\(end.*)\;/g' test

I was hoping the /if/! would omit all literal if strings from the next command but when I attempt to run it I receive the following error:

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

Can anyone help me understand why I'm getting that error please? And if the sed command is mainly correct, if not what would you recommend to improve it.


Thank you! As suggested I've tried adding in an extra / at the end as I just require it removing not replaced. But now I have this error: sed -i -e '/if/! s/\(end.*)\;//' test sed: -e expression #1, char 20: Unmatched ( or \(

To me it looks like I have a closing bracket not too sure about the '\' . I have only done this a once before, so quite new.

  • The correct syntax is: s/pattern/replacement/modifiers, but you have s/pattern/modifiers (missing replacement).
    – pLumo
    Jun 10, 2020 at 9:20
  • Thank you, I have updated my post as I'm still quite confused
    – Jack
    Jun 10, 2020 at 9:28

1 Answer 1

  1. Your first attempt misses the replacement part from s/pattern/replacement/modifiers syntax.

  2. You forgot to escape the closing bracket: Use \).

  3. No need to escape the semicolon though.

  4. Your pattern includes all of end.*;. So all this will get removed. Use \1; as replacement.

In total:

sed -i -e '/if/!s/\(end\).*;/\1;/' file

Or as end is a static word and .* includes the ; you can simplify it:

sed -i -e '/if/!s/end.*/end;/' file
  • Thank you, that was a good explanation makes a lot of sense. If I also needed to omit another word from the removal, would it be a case of adding another /<word>/! either before or straight after the if one, or is it more complex than that?
    – Jack
    Jun 10, 2020 at 10:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.