Grep/Awk on 1st 2 Letters in 2nd Column of File

Hi everyone. I need to change a script (ksh) so that it will grep on the 1st 2 letters in the second column of a 5 column file such as this one:

192.168.1.1   CAXY0_123   10ABFL000001   #   Comment
192.168.1.2   CAYZ0_123   10ABTX000002  #   Comment
192.168.2.1   FLXY0_123   11ABCA000001   #   Comment
192.168.2.2   FLYZ0_123   11ABTX000002   #   Comment
192.168.3.1   TXXY0_123   12ABCA000001  #   Comment
192.168.3.2   TXYZ0_123   12ABFL000002   #   Comment

...and print the entire line in which the match was found.

For example, I need to grep/awk for 'CA' in the CAXY0_123 and CAYZ0_123 entries in the first 2 lines of the file so that the resulting output will be:

192.168.1.1   CAXY0_123   10ABFL000001   #   Comment
192.168.1.2   CAYZ0_123   10ABTX000002  #   Comment

Can someone let me know how this can be done? I've been googling myself crazy and checking previous forum posts here but have found nothing that applies to this exact situation. I also haven't had any luck playing around with the grep/awk/nawk commands with which I'm already familiar.

Thanks!

Hi

$ awk '$2 ~ /^CA/' file
192.168.1.1 CAXY0_123 10ABFL000001 # Comment
192.168.1.2 CAYZ0_123 10ABTX000002 # Comment

Guru.

1 Like

With grep:

grep ' CA' file

192.168.1.1 CAXY0_123 10ABFL000001 # Comment
192.168.1.2 CAYZ0_123 10ABTX000002 # Comment

or (with some assumptions):

grep -E '^([0-9]{1,3}\.){3}[0-9]{1,3} CA' file

Hey guys. Thanks for the quick replies. I tried the suggestions below on the acutal file (~40000 entries) and, after cross checking the output with another source, I appeared to get the most accurate results with Guru's code (awk '$2 ~ /^CA/' file).

I'll be making note of all of the suggestions below for future reference, though.

Thanks again! You guys just saved me a bunch of time.