Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the last 2 characters of a string with last character being A or B and second to the last character being 1-360? (REGEX GREP)

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

Try this:

cat input-file | perl -ne 'print "$1\n" if (m/([0-9]+[AB])$/)'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading