Arzaan Ul
Arzaan Ul

Reputation: 13

Sed is not matching a backslash literal or am I doing something wrong?

I have a file which has 3 lines:

%fddfdffd
\%dffdfd
hello %12345678

I need to remove anything after "%" character (inlcuding the "%" character) but not if the "%" begins with a "\".

I tried this but it didn't work:

sed -i "s/[^\\]%.*//g"

The task is actually working on a latex file to remove the comments using sed

The file after using sed should be:

\%dffdfd
hello 

Upvotes: 0

Views: 111

Answers (2)

potong
potong

Reputation: 58508

This might work for you (GNU sed):

sed -E 's/(^|[^\])%.*/\1/' file

If the line starts with a % or % follows any character other than \, delete the rest of the line.

If as a consequence the line is empty and is also to be deleted, use:

sed -E '/^%/d;s/([^\])%.*/\1/' file

Upvotes: 1

Cyrus
Cyrus

Reputation: 88829

I suggest with your three cases:

sed '/^%/d; /\\%/b; s/%.*//' file

Output:

\%dffdfd
hello 

See: man sed

Upvotes: 2

Related Questions