4

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.

2
  • Is awk required? Can you use fgrep / grep -F?
    – jw013
    Commented Aug 29, 2012 at 18:18
  • awk is required
    – Tyilo
    Commented Aug 29, 2012 at 18:20

2 Answers 2

7

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'
1
  • I need it to match where the string is a substring also, sorry.
    – Tyilo
    Commented Aug 29, 2012 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
  • 1
    echo "[(*.+" | gawk '"wtf"' will also display the same result as your example, but still not solves the problem.
    – manatwork
    Commented Aug 30, 2012 at 9:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .