Take the 2-minute tour ×
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.

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.

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
add comment

2 Answers

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
add comment

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
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
add comment

Your Answer

 
discard

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.