I want to delete anything that follows a % to the end of the line. Using

cat /tmp/foo.txt | sed 's/%.*$//'

works great with one exception: I want to ignore any escaped percent signs \%. So with the following file saved as /tmp/foo.txt

abcd %123
xyz \%xyz
xyz \%xyz %123

the output I want is

xyz \%xyz
xyz \%xyz

What is the appropriate regular exception handling to do this?

1 Answer 1


You need to look at the character before the percent.

sed 's/\([^\\]\)%.*/\1/'

If the previous character is not a backslash, keep that char and remove the rest.

This answer assumes that the % does not appear at the beginning of the line. If it does, then we need to check for it

sed 's/\(^\|[^\\]\)%.*/\1/'
  • The first version does what was asked. The second version doesn't seem to do anything (fails to remove any characters). Apr 14, 2015 at 15:37
  • Can be simplified be GNU sed 's/ %.*//g'
    – Costas
    Apr 14, 2015 at 16:13
  • @Costas: While he didn't include any examples that look like this, the OP's statement "I want to delete anything that follows a % to the end of the line" ... (with one exception) implies that he wants to change foo%bar to foo. Apr 14, 2015 at 16:47
  • 2
    @PeterGrill: sed -e 's/\([^\\]\)%.*/\1/' -e 's/^%.*//' might be the hybrid command that you need to handle % at any position in the line (including the first character). Apr 14, 2015 at 16:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .