I have numbers starging with a special character @ and ending with 900 and I now I want to extract the text in between excluding them.
My code:
>> cat demo.txt
asdfsdf
@ 1234900 asdf dfasd
asdf @ 1345900-asdfad wer
@ 678900-asdfa adf
>> grep -Po '@\K.*900' demo.txt
1234900
1345900
678900
Expected answer:
1234
1345
678
CodePudding user response:
You can use
grep -oP '@\s*\K\d ?(?=900)'
See the regex demo. Details:
-o- the option makesgrepoutput all matched substrings rather than lines where a match occurredP- enables the PCRE regex engine rather than the default POSIX BRE@- a@char\s*- zero or more whitespaces\K- match reset operator discarding all text matched so far\d ?- one or more digits, as few as possible(?=900)- until the first, leftmost, occurrence of900char sequence.
See the online demo:
#!/bin/bash
s='asdfsdf
@ 1234900 asdf dfasd
asdf @ 1345900-asdfad wer
@ 678900-asdfa adf '
grep -oP '@\s*\K\d ?(?=900)' <<< "$s"
Output:
1234
1345
678
