Shell – Match pattern in a file and print the matching word (not the whole line) in second column

awksedshell-scripttext processing

I am trying to match the pattern "SHM" in a file containing like the below information and print the word matching the pattern.

LOCALZONE01     ASHM001002003VOL01
                BSHM001002003VOL02
                CSHM001002003VOL03
                DSHM001002003VOL03_DUP
                ESHM001002003VOL04
                FSHM001002003VOL05
                GSHM001002003VOL06_
                HSHM001002003VOL07

I have tried to use awk to print the 2nd column:

grep "SHM" <filename.txt> | awk -F" " '{print $2}'

ASHM001002003VOL01

If I try to print column 1, it’s giving me the below output:

LOCALZONE01
BSHM001002003VOL02
CSHM001002003VOL03
DSHM001002003VOL03_DUP
ESHM001002003VOL04
FSHM001002003VOL05
GSHM001002003VOL06_
HSHM001002003VOL07

Below is my desired output. How can I get it?

ASHM001002003VOL01
BSHM001002003VOL02
CSHM001002003VOL03
DSHM001002003VOL03_DUP
ESHM001002003VOL04
FSHM001002003VOL05
GSHM001002003VOL06_
HSHM001002003VOL07

Best Answer

If the output you want is always the last field in the file, try this

awk '{if ($NF ~ /SHM/) {print $NF}}' _input_file_
Related Question