Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a word before and after a pattern (Hyphen is the pattern ) on shell script

Tags:

shell

sed

awk

Select a word before and after a pattern (Hyphen is the pattern) using shell script.

Out is a text file which has hundreds of lines and i have selected the ones which has Required ID's, however i need to select ALPHABETS-NUMBERS. Count of Alphabet and Number varies.

I have tried various utilities including cut, sed, awk, however it s trimming the required fields.

Input

cat out | grep "[A-Z][-][0-9]"
BUG-KEYWORD-BUG-101
ABC-10
DEF-10327
Output is referred in ABC-1043
Please refer DEF-11234

Output Should be

BUG-101
ABC-10
DEF-10327
ABC-1043
DEF-11234
like image 394
Raj Avatar asked Feb 04 '21 09:02

Raj


1 Answers

Could you please try following. Written and tested with shown samples in GNU awk.

awk 'match($0,/[a-zA-Z]+-[0-9]+$/){print substr($0,RSTART,RLENGTH)}' Input_file

Explanation: Adding detailed explanation for above.

awk '                               ##Starting awk program from here.
match($0,/[a-zA-Z]+-[0-9]+$/){      ##using match function to match alphabets dash and digits till last of line.
  print substr($0,RSTART,RLENGTH)   ##Printing matches sub string of matched regex.
}
' Input_file                        ##Mentioning Input_file name here.
like image 180
RavinderSingh13 Avatar answered Nov 15 '22 10:11

RavinderSingh13