AWK match exact string inside square brackets

Viewed 789

I have a file similar to the below-illustrated data.

https://www.test.example.com [503]
https://www.tst.example.com [403]
https://www.tt.example.com [302]

I want to fetch lines that match with the second column. For example, lines matching [403] should print only https://www.tst.example.com.

I tried escaping the square brackets with the below command, which gave me a warning.

$ awk -F "$2 == '\[403]\'" file.txt
awk: warning: escape sequence `\[' treated as plain `['
awk: warning: escape sequence `\'' treated as plain `''
3 Answers

You are mixing regular expressions and plain strings. [ is a regex special character, but you are not using a regex here, just a literal string comparison. You don't need any escaping at all (though you might want to reverse the usage of single and double quotes for simplicity, unless you are actually using Windows).

awk '$2 == "[403]"' file.txt

In basically all the Unix shells, the double quotes you used don't protect dollar signs, so $2 would be substituted by the shell, probably with nothing, or else with some unrelated string (whatever got passed in as the second command-line argument to the shell).

The -F option, if present, requires an argument; but based on your example data, the default field separator - any sequence of whitespace - should work fine. If you want to force it to e.g. a single space, try -F ' '.

Could you please try following, written and tested with shown samples in GNU awk.

awk -F'([[:space:]]*)?\\[|\\]([[:space:]]*)?' '$2=="403"{print $1}' Input_file

Explanation: Setting field separator as either spaces(optional)[ OR [spaces(optional) for all lines. Then checking if 2nd field is 403 then print the first field as per OP's request.

Will do what you want, with the benefit of allowing you to pass the desired code as an argument, rather than having it hardcoded into the awk script.

awk -v http_code=403 '$2 == "["http_code"]"' file.txt
Related