Hasitha
Hasitha

Reputation: 95

How to include "[" and "]" in awk pattern search

I have following code in a bash script

stat_pattern="POSITION_UPDATE [ For INRecord ]"
cat my_file.txt | awk -v pattern="$stat_pattern" '$0 ~ pattern' | tail -n 1 

but it does not return any output. I tried "\" also with "[". buy it did not help also.

Please tell me how to treat "[" "]" characters as a part of search string...

Upvotes: 2

Views: 114

Answers (3)

anubhava
anubhava

Reputation: 785856

Remember tilde operator ~ in awk treats matching string as a Regular Expression and if you have special regex characters ([ and ] in your case) then regex matching will fail. For your case its better to use an awk function index(in, find) to find a string inside another string like this code:

awk -v pattern="$stat_pattern" 'index($0, pattern) {line=$0} 
       END{print line}' my_file.txt 

Also note that you has unnecessary cat and tail piped in to your command. All that can be done in awk itself therefore I refactored your commands.

Upvotes: 2

parkydr
parkydr

Reputation: 7792

You have to escape the '[' and the '\' so it should be

stat_pattern="POSITION_UPDATE \\\[ For INRecord \\\]"

Upvotes: 0

janos
janos

Reputation: 124744

You must escape the escape character, like this:

stat_pattern='POSITION_UPDATE \\[ For INRecord \\]'

Upvotes: 0

Related Questions