Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.


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

share|improve this question
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
up vote 5 down vote accepted

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'
share|improve this answer
I need it to match where the string is a substring also, sorry. – Tyilo Aug 29 '12 at 18:22

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 [^: /[(*.+//
share|improve this answer
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 posting your answer, you agree to the privacy policy and terms of service.

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