4

I am trying to grep for only for a range of numbers located inside parenthesis. My current grep will pull everything within the parenthesis but I just want anything from [0001-9999]. How can I fix my grep to do this?

I have tried a few different version of this (?<=\()[0001-9999](?=\)) but they don't return anything

$ cat /tmp/output
This is R3trans version 6.26 (release 745 - 24.03.17 - 20:17:03).
R3trans finished (0000).
R3trans finished (0001).
R3trans finished (9999).
05.03.2018 16:30:02
enserver, EnqueueServer, RED, Running, 2018 02 27 09:15:52, 151:14:10, 19069

Current output

$ cat /tmp/output | grep -Po '(?<=\().*(?=\))'
release 745 - 24.03.17 - 20:17:03
0000
0001
9999

Desired output

$ cat /tmp/output | grep -Po '(?<=\().*(?=\))'
0001
9999
  • You want only four digit numbers? Why is [0-9]{4} not working? Or, if your RE implementation does not support curly-brace counters, [0-9][0-9][0-9][0-9]? – DopeGhoti Mar 6 '18 at 17:29
  • That is close but I only want 0001 to 9999 $ cat /tmp/output | grep -Po '(?<=\()[0-9]{4}(?=\))' 0000 0001 9999 – SpruceTips Mar 6 '18 at 17:32
  • So take that and strip out 0000 with an inverse search. – DopeGhoti Mar 6 '18 at 17:37
8

Two approaches to reach the goal:

grep approach (with Perl support):

grep -Po '\(\K(?!0000)([0-9]{4})(?=\))' /tmp/output

GNU awk approach:

awk -v FPAT='\\([0-9]{4}\\)' '$1{ n = substr($1,2,4); if (int(n) > 0) print n }' /tmp/output

The output:

0001
9999
3

Apparently you have numeric constrains. If this is the case, why not using a programming language? Example:

perl -nE '/\((\d{4})\)/ and $1 > 0 and say $1'
  • 1
    (assuming there's only one occurrence per line) – Stéphane Chazelas Mar 6 '18 at 17:44
3

This appears to work:

grep -Eo '[0-9]{4}' /path/to/file | grep -v '0000'

Less readable, but with only one grep:

grep -Eo '[0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]|[0-9][1-9][0-9]{2}|[1-9][0-9]{3}' /path/to/file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.