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
Value
Unknown dbs636294051.klm.bet.com: /opt
N/A
Unknown dbs636294051.klm.bet.com: /tmp
N/A
Unknown dbs636294051.klm.bet.com: /var
N/A

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:

dbs636294051.klm.bet.com
dbs636294051.klm.bet.com
dbs636294051.klm.bet.com

>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

Output

dbs636294051.klm.bet.com
dbs636294051.klm.bet.com
dbs636294051.klm.bet.com

Leave a Reply