开发者

Grep. Line of text that does not end with "abcd"?

Hi I'm looking for a regular expression for: line of text that does not end with a certain word, let's say it's "abcd"

At first I tried with

.*[^abcd]$

That one doesn't work of course. It matches a line that开发者_JAVA技巧 doesn't end with any of the letters a,b,c or d.

So, in Advanced Grep Topics, I found this expression, but couldn't get it to work:

^(?>.*)(?<=abcd)

->

grep -e "^(?>.*)(?<=abcd)$"

Any idea for the expression I need?


Have a look at grep's -v option

grep -v 'abcd$'

If you really meant word rather that just "sequence of characters" then use

grep -v '\babcd$'

\b meaning "word-boundary"


Give this a shot:

grep -v "\<abcd\>$"

Proof of Concept

$ printf "%s\n" "foo abcd bar baz" "foo bar baz abcd" "foo bar bazabcd" | grep -v "\<abcd\>$"
foo abcd bar baz
foo bar bazabcd

Note: This will match whole words as noted by the fact that the 3rd line was returned even though it contained abcd as the last 4 letters


grep supports PCRE regular expressions when using -P flag.

One of the reason grep -e "^(?>.*)(?<=abcd)$" does not work is because the lookaround you are using is positive, which means totally opposite of what is required. (?<= is the syntax for positive lookbehind, which tells regex engine to search for lines that ends with abcd.

To search for lines that does not end with certain string, you need to use negative lookbehind. The syntax for negative lookbehind is (?<!. And because negative lookbehind includes exclamation mark which bash will try to interpret as an event, one can not use double quotes to supply regex to grep.

I used following regex to search for the lines that do not end with log.

grep -P '(?<!log)$' < <inputfile>

Similarly you can use above command and replace log with whatever pattern you want to match.

This regex can be used with other programs where inverse matching is not supported, such as -v option of grep

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜