-1

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?

Daemon Painter
  • 3,208
  • 3
  • 29
  • 44
  • I cannot recreate this after setting test_var="abc[0]". I'm assuming this is what you did? – Raman Sailopal Jan 11 '21 at 15:14
  • 2
    Please read https://stackoverflow.com/questions/65621325/how-do-i-find-the-text-that-matches-a-pattern and then replace "pattern" with "regexp" or "string", whichever it is you mean, everywhere in your question. – Ed Morton Jan 11 '21 at 15:28
  • I want to do find a variable pattern by awk command . Example - echo "test abc[0]" | awk -v variable="abc[0]" '$0 ~ variable {print variable}' – Vishal Patel Jan 11 '21 at 17:19
  • 1
    **please** read the link I provided to understand why use of the word "pattern" instead of regexp or string and with no indication of partial/full matching makes your question ambiguous. – Ed Morton Jan 11 '21 at 23:35

1 Answers1

0

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
karakfa
  • 66,216
  • 7
  • 41
  • 56