Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

awk with variable pattern with square paranthesis

In my variable pattern there is square parentheses ( abc[0] ), but awk is unable to find pattern. If I change my pattern from abc[0] to abc_0, then it works.

echo "test_var=$test_var, test_var_1=$test_var_1"
# Output - test_var=abc[0], test_var_1=abc[0]

echo "$test_var" | awk -v variable="$test_var_1" '$0 ~ variable {print $variable}'
# "NO OUTPUT"  



echo "test_var=$test_var, test_var_1=$test_var_1"
# test_var=abc_0, test_var_1=abc_0

echo "$test_var" | awk -v variable="$test_var_1" '$0 ~ variable {print $variable}'
# Here Output is abc_0

How to find pattern variable which has square parenthesis by awk command?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

square brackets are special regex characters.

Check the following three cases, perhaps it will clarify

$ awk 'BEGIN{if("abc[0]" ~ /abc[0]/) print "match"; else print "no match"}'
no match


$ awk 'BEGIN{if("abc0" ~ /abc[0]/) print "match"; else print "no match"}'
match


$ awk 'BEGIN{if("abc[0]" ~ /abc[0]/) print "match"; else print "no match"}'
match

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...