2

How do I match a string with AWK?

Say I have the string [(*.+ it should only match strings containing the string [(*.+.

The string is entered by the user, so if you know a cli utility that can escape regexes it may work too.

Edit:

It should also match strings containing the string, such as foo[(*.+bar.

  • Is awk required? Can you use fgrep / grep -F? – jw013 Aug 29 '12 at 18:18
  • awk is required – Tyilo Aug 29 '12 at 18:20
5

awk does string comparison with the == operator, and string searching with the index(haystack, needle) function.

read -r string # user types [(*.+
{ echo 'stuff [(*.+ stuff'; echo ')]*.+'; } | awk -v string="$string" 'index($0, string)'
# output: 'stuff [(*.+ stuff'
  • I need it to match where the string is a substring also, sorry. – Tyilo Aug 29 '12 at 18:22
0

Basically, awk treats chars within "" as string and within // as regexp:

[root@me ~]# echo "[(*.+" | gawk '"[(*.+"'
[(*.+
[root@me~]# echo "[(*.+" | gawk '/[(*.+/'
gawk: /[(*.+/
gawk:  ^ unterminated regexp
gawk: fatal: Unmatched [ or [^: /[(*.+//
  • 1
    echo "[(*.+" | gawk '"wtf"' will also display the same result as your example, but still not solves the problem. – manatwork Aug 30 '12 at 9:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.