3

I have strings like this:

ACB 01900 X1911D 1910 1955-2011 3424 2135 1934 foobar

I'm trying to get the last occurrence of a single year (from 1900 to 2050), so I need to extract only 1934 from that string.

I'm trying with:

 grep -P -o '\s(19|20)[0-9]{2}\s(?!\s(19|20)[0-9]{2}\s)'

or

grep -P -o '((19|20)[0-9]{2})(?!\s\1\s)'

But it matches: 1910 and 1934

Here's the Regex101 example:

https://regex101.com/r/UetMl0/3

https://regex101.com/r/UetMl0/4

Plus: how can I extract the year without the surrounding spaces without doing an extra grep to filter them?

6
  • 2
    With awk: awk 'BEGIN{RS=" "} /^(19|20)..$/{y=$0} END{print y}'
    – Cyrus
    Commented Dec 2, 2018 at 16:55
  • 1
    @Cyrus That only works if your input is a single line. It will only extract one number from the whole input file. I'm assuming OP wants the last number from each line.
    – melpomene
    Commented Dec 2, 2018 at 17:04
  • 1
    @Cyrus Doesn't work if the number is the last field of the line.
    – melpomene
    Commented Dec 2, 2018 at 17:06
  • 1
    @melpomene yes but as I have a new single string for each loop it can be a solution
    – Kintaro
    Commented Dec 2, 2018 at 17:07
  • 1
    @melpomene: Good point. Unfortunately it doesn't work with the year number in the last column.
    – Cyrus
    Commented Dec 2, 2018 at 17:11

4 Answers 4

2

Have you ever heard this saying:

Some people, when confronted with a problem, think
“I know, I'll use regular expressions.”   Now they have two problems. 

Keep it simple - you're interested in finding a number between 2 numbers so just use a numeric comparison, not a regexp:

$ awk -v min=1900 -v max=2050 '{yr=""; for (i=1;i<=NF;i++) if ( ($i ~ /^[0-9]{4}$/) && ($i >= min) && ($i <= max) ) yr=$i; print yr}' file
1934

You didn't say what to do if no date within your range is present so the above outputs a blank line if that happens but is easily tweaked to do anything else.

To change the above script to find the first instead of the last date is trivial (move the print inside the if), to use different start or end dates in your range is trivial (change the min and/or max values), etc., etc. which is a strong indication that this is the right approach. Try changing any of those requirements with a regexp-based solution.

1
  • 2
    This makes sense a lot. Thank you Ed.
    – Kintaro
    Commented Dec 3, 2018 at 21:23
2

I don't see a way to do this with grep because it doesn't let you output just one of the capture groups, only the whole match.

Wit perl I'd do something like

perl -lpe 'if (/^.*\b(19\d\d|20(?:0-4\d|50))\b/) { print $1 }'

Idea: Use ^.* (greedy) to consume as much of the string up front as possible, thus finding the last possible match. Use \b (word boundary) around the matched number to prevent matching 01900 or X1911D. Only print the first capture group ($1).

I tried to implement your requirement of 1900-2050; if that's too complicated, ((?:19|20)\d\d) will do (but also match e.g. 2099).

2

The regex to do your task using grep can be as follows:

\b(?:19\d{2}|20[0-4]\d|2050)\b(?!.*\b(?:19\d{2}|20[0-4]\d|2050)\b)

Details:

  • \b - Word boundary.
  • (?: - Start of a non-capturing group, needed as a container for alternatives.
    • 19\d{2}| - The first alternative (1900 - 1999).
    • 20[0-4]\d| - The second alternative (2000 - 2049).
    • 2050 - The third alternative, just 2050.
  • ) - End of the non-capturing group.
  • \b - Word boundary.
  • (?! - Negative lookahead for:
    • .* - A sequence of any chars, meaning actually "what follows can occur anywhere further".
    • \b(?:19\d{2}|20[0-4]\d|2050)\b - The same expression as before.
  • ) - End of the negative lookahead.

The word boundary anchors provide that you will not match numbers - parts of longer words, e.g. X1911D.

The negative lookahead provides that you will match just the last occurrence of the required year.

If you can use other tool than grep, supporting call to a previous numbered group (?n), where n is the number of another capturing group, the regex can be a bit simpler:

(\b(?:19\d{2}|20[0-4]\d|2050)\b)(?!.*(?1))

Details:

  • (\b(?:19\d{2}|20[0-4]\d|2050)\b) - The regex like before, but enclosed within a capturing group (it will be "called" later).
  • (?!.*(?1)) - Negative lookahead for capturing group No 1, located anywhere further.

This way you avoid writing the same expression again.

For a working example in regex101 see https://regex101.com/r/fvVnZl/1

2

You may use a PCRE regex without any groups to only return the last occurrence of a pattern you need if you prepend the pattern with ^.*\K, or, in your case, since you expect a whitespace boundary, ^(?:.*\s)?\K:

grep -Po '^(?:.*\s)?\K(?:19\d{2}|20(?:[0-4]\d|50))(?!\S)' file

See the regex demo.

Details

  • ^ - start of line
  • (?:.*\s)? - an optional non-capturing group matching 1 or 0 occurrences of
    • .* - any 0+ chars other than line break chars, as many as possible
    • \s - a whitespace char
  • \K - match reset operator discarding the text matched so far
  • (?:19\d{2}|20(?:[0-4]\d|50)) - 19 and any two digits or 20 followed with either a digit from 0 to 4 and then any digit (00 to 49) or 50.
  • (?!\S) - a whitespace or end of string.

See an online demo:

s="ACB 01900 X1911D 1910 1955-2011 3424 2135 1934 foobar"
grep -Po '^(?:.*\s)?\K(?:19\d{2}|20(?:[0-4]\d|50))(?!\S)' <<< "$s"
# => 1934
1
  • 2
    This is working 100% and solved another problem too, with some others I was getting Value too great for base (error token is “XXXXX”).
    – Kintaro
    Commented Dec 3, 2018 at 8:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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