awk Regular Expression – How to Perform Case-Insensitive Search in awk

awkregular expression

I need to search for a keyword using awk, but I want to perform a case-insensitive (non case sensitive) search.

I think the best approach is to capitalize both the search term ("key word") and the target line that awk is reading at the same time. From this question I how to use toupper to print in all uppercase, but I don't know how to use it in a match because that answer just shows printing and doesn't leave the uppercase text in a variable.

Here is an example, given this input:

blablabla    
&&&Key Word&&&
I want all 
these text and numbers 123
and chars !"£$%&
as output
&&&KEY WORD&&&
blablabla

I'd like this output:

I want all 
these text and numbers 123
and chars !"£$%&
as output

This is what I have, but I don't know how to add in toupper:

awk "BEGIN {p=0}; /&&&key word&&&/ { p = ! p ; next } ; p { print }" text.txt

Best Answer

Replace your expression to match a pattern (i.e. /&&&key word&&&/) by another expression explicitly using $0, the current line:

tolower($0) ~ /&&&key word&&&/

or

toupper($0) ~ /&&&KEY WORD&&&/

so you have

awk 'tolower($0) ~ /&&&key word&&&/ { p = ! p ; next }; p' text.txt

You need single quotes because of the $0, the BEGIN block can be removed as variables are initialised by default to "" or 0 on first use, and {print} is the default action, as mentioned in the comments below.

Related Question