I'm not really using regex in a daily basis and I'm still new to this.
For example, I have these strings and this is the format of the strings: ( APPLE20B50A, APPLE30A60B, APPLE12B5B, APPLE360A360B, APPLE56B, ORANGE55B300A MANGO22A120B
Basically, I want to get the last letter (A or B) and the digit before the last letter (or a digit after the letter/before the digit which is also A or B too). There are also a format like APPLE56B that doesn't have digit letter in the middle.
Expected Output:
50A 60B 5B 360B 56B 300A 120B
I tried grep -o '.{2}$' but it only outputs the last 2 characters:
0A 0B 5B 0B 6B
and obviously, it's not dynamic for the digits. Any help would be appreciated.
Thanks!
CodePudding user response:
Try this:
cat input-file | perl -ne 'print "$1\n" if (m/([0-9] [AB])$/)'
CodePudding user response:
grep -o
would indeed work with the correct pattern
grep -oP '[0-9] [AB]$'
With Perl,
perl -nle'print for /([0-9] [AB])$/'
In both cases, you can provide the input via STDIN or by passing a file name to read as an argument.