Linux – How to search a string starting from second column

awklinux

I have a file that contains comma separated strings. The strings may contain dots (i.e. not just alphanumeric characters). This is an example:

site1.com,Level1.2
site2.com,Level1.1,Level1.0,Level1.2
site3.com,Level1.2
site4.com,Level1.2,Level1.1,Level1.0,Levelv3
siteLevel1.2,Levelv2
Level1.2,Levelv2

I need to do search for the site names (please note that I do not have specific format for site name, i.e. it does not end with .com always so I should not conside how the first column look like)

I need the sites that ONLY contains specific string. In this example, Level1.2 exclusively (without Level1.1 nor Level1.0 not Level3 either before or after). Then print the result in a new file that matches the condition (only contains Level1.2). So the search key words are starting from the second column (I do not want search result that finds matching pattern in the site name).

So if I'm searching for Level1.2, the new file should contain:

site1.com,Level1.2
site3.com,Level1.2

But my command result in:

site1.com,Level1.2
site3.com,Level1.2
siteLevel1.2,Levelv2
Level1.2,Levelv2

If there is a site that contains Level1.2 in its name, it should not be counted as I do not care about the first column.

I tried this command and it works for me. The only thing is that I need the searching to ignore the occurrence of the search string in the first column.

awk '/Level1.2/ && !/Level1.1/ && !/Level1.0/ !/Level3/' myfile.txt > result.txt

Best Answer

You can try this awk:

awk -F, '$2=="Level1.2" && NF==2' myfile.txt

The input delimiter is set to ,. The command prints lines containing 2 fields with the second one having the matching string.

Related Question