Recently I come across a requirement to search for lines in a given file/files where the search term is mix of capital letters and small letters. Normally when we search with awk it search exactly what we try to search but not ignoring case. We can use grep to accomplish this task as sown below.
grep -i 'available' files | awk '{print $1,$2}'
But I don't want to use grep to do this as there is a way we can accomplish with just awk. We can specify ignoring case to AWK in three ways as mention below.
Use AWK builtin variable called IGNORECASE enable ignore case switch with search pattern Use not so sophisticated method of using both cases in search term
Let see these three in examples.
Example1: Search for a word 'available' which some times written as Available or AVAILABLE. Using IGNORECASE AWK inbuilt variable example as below
awk 'BEGIN{IGNORECASE=1} /available/{print $1}' filename
BEGIN is an AWK keyword which is useful to execute awk code before actual AWK script. We are setting IGNORECASE before our actual AWK code execution.
Example2: Search for word 'available' using 'i' switch so that my match will have both cases
awk '/available/i {print $1}' filename
if you observe after serach pattern we given /i which will help us to ignore case with our search term.
Example3: Search for 'available' word with combination of cases which will not work in all the cases
awk '/[aA][vV][aA][iI][lL][aA][bB][lL][eE]/ {print $1}' filename
Hope this helped some one when trying to shorten your code.
Latest posts by Surendra Anne (see all)
- Docker: How to copy files to/from docker container - June 30, 2020
- Anisble: ERROR! unexpected parameter type in action:
Fix - June 29, 2020 - FREE: JOIN OUR DEVOPS TELEGRAM GROUPS - August 2, 2019
- Review: Whizlabs Practice Tests for AWS Certified Solutions Architect Professional (CSAP) - August 27, 2018
- How to use ohai/chef-shell to get node attributes - July 19, 2018