Awk based filtering of data on a file in Linux


I have a file data which are trying to filter via awk, i am able to filter the data but want the awk statement to be simpler into one line:

File contents:

Entity Name
Unknown /opt
Unknown /tmp
Unknown /var

My trial:

awk  '!/^N/{ if($2 ~ /klm/) print $2}' file | awk -F":" '{print $1}'

The above works but i’m looking if this can be trimmed to the before pipe line:

>Solution :

You can write a single awk command, setting the field separator to 1 or more spaces or :, check if field 1 does not start with N ad that it does contain klm

To be really specific, you could also write ^N\/A$

Thanks to the comments of @Renaud Pacalet and @Wiktor Stribiżew the command can look like:

awk -F'[[:blank:]]+|:' '!/^N/ && $2 ~ /klm/{print $2}' file

In parts

awk -F'[[:blank:]]+|:' '   # Set the field separator to either 1+ spaces or tabs or a semicolon
!/^N/ && $2 ~ /klm/        # If the record does not start with `N` and field 2 does contain klm
{print $2}                 # Print the second column


Leave a ReplyCancel reply