Home > other >  grep for entries that do not contain a backtick before and after a regexp
grep for entries that do not contain a backtick before and after a regexp

Time:07-26

I have a text file with the following content:

Read the `lmn(7)` man page but not qrs(6).
* abc(1)
* `efg(3)`
* `ijk(1)`
* xyz(5)

I want now to filter for all lines that contain a man page name that is not in backticks? The expected output is:

Read the `lmn(7)` man page but not qrs(6).
* abc(1)
* xyz(5)

For demonstration purposes, I need this as a single grep command and not with other tools or piped.

I tried the following, but it only returns the first line:

$ egrep '[^`][a-z]*\([0-9]\)[^`]'

CodePudding user response:

It doesn't match the other lines because there's no character after the ) to match [^`]. You need to add an alternative to match the end of the line. And you should have a similar alternative for the first backtick to match the beginning of the line.

grep -E '(^|[^`])[a-z]*\([0-9]\)([^`]|$)'

CodePudding user response:

This grep -v should work for with the given examples:

grep -v '^\* `' file

Read the `lmn(7)` man page but not qrs(6).
* abc(1)
* xyz(5)

We are just filtering out lines that start with * ` using grep -v.

CodePudding user response:

If these matches occur without a backtick between the match and the end of the string:

grep -E '[^`][a-z]*\([0-9]\)[^`]*$' file

Output

Read the `lmn(7)` man page but not qrs(6).
* abc(1)
* xyz(5)
  • Related