0

I have strings like this in a file on unix machine

26 3 24 21 391
26 34 24
26 3 49 24 21 391
26 94 24
26 3 21 391
26 3 
27 3 24 21 391
2 94

Now I want to match more than one numbers at a time. These numbers are fixed ( constants) and doesn't need matching pattern to recognise them. So here if I want to match either 94 or 24 I will use below expression.

grep '\b\(94\|24\)\b' file_name.txt

But I actually need to find those string which has neither 94 nor 24. That means I want all the rows which not contains any of these numbers. I don't want to use options which come with grep ( like -v ).

EDIT: Expected output -

26 3 21 391
26 3 
user2611539
  • 336
  • 1
  • 4
  • 11

1 Answers1

0

You cannot write a POSIX pattern to match a string not containing some multicharacter pattern.

You may use

grep -Ev '\b[29]4\b' file

The -E option enables the POSIX ERE compliance, the \b[29]4\b pattern matches 2 or 8 and then 4 as a whole word, and v inverts the results of a match.

See the online demo.

You may also use a PCRE regex without v option if your grep supports it:

grep -P '^(?!.*\b[29]4\b)' file

The P enables the PCRE regex engine, ^(?!.*\b[29]4\b) matches the start of string with ^ and then fails all matches if, after 0+ chars, there is a 24 or 94 value as a whole word.

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
  • 1
    Thanks but as I have mentioned in my question, I can't use options which come with grep command. – user2611539 Oct 01 '18 at 10:38
  • @user2611539 Why don't you? BTW, what is your `grep` version? – Wiktor Stribiżew Oct 01 '18 at 10:39
  • 1
    I would be passing this regular expression to some other code which I don't have access to. I have to achieve it through Regex only. – user2611539 Oct 01 '18 at 10:40
  • 1
    @user2611539 It will be only possible if that code will parse the pattern with PCRE regex engine. Else, you can't do that with `grep` because you cannot write a POSIX pattern to match a string not containing some pattern. – Wiktor Stribiżew Oct 01 '18 at 10:43
  • If anyone thinks there is a way to write such a POSIX pattern, I'd be glad to add an example to my [Regex: match everything but](https://stackoverflow.com/a/37988661/3832970) answer. – Wiktor Stribiżew Oct 01 '18 at 10:47