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:
APPLE20B 50A
APPLE30A 60B
APPLE12B 5B
APPLE360A 360B
APPLE 56B
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
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.
grep -o
would indeed work with the correct pattern
grep -oP '[0-9]+[AB]$'
With Perl,
perl -nle'print $& if /[0-9]+[AB]$/'
perl -nle'print for /([0-9]+[AB])$/'
In all cases, you can provide the input via STDIN or by passing a file name to read as an argument.
Try this:
cat input-file | perl -ne 'print "$1\n" if (m/([0-9]+[AB])$/)'
This might work for you (GNU grep):
grep -o '\(360\|3[0-5][0-9]\|[1-2][0-9][0-9]\|[1-9][0-9]\|[1-9]\)[AB]\>' file
This will print each value on a separate line from 1A/1B
to 360A/360B
.
To space separate these values use:
grep -o '\(360\|3[0-5][0-9]\|[1-2][0-9][0-9]\|[1-9][0-9]\|[1-9]\)[AB]\>' file |
paste -sd' '
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.