简体   繁体   中英

Awk use shell variable inside begin block

Below is a file named sites.txt:

google is good
yahoo is dying
microsoft is ok
faceBook is vulnerable

Script::

#!/bin/bash

site="facebook"

awk -v s="$site" 'BEGIN {IGNORECASE = 1} /s/' sites.txt

But the above command does not return any output. How can I use a shell variable inside the begin block to display correct output.

Your command is literally matching s in every line.

You should be using ~ operator:

awk -v s="$site" 'BEGIN {IGNORECASE = 1} $0 ~ s' sites.txt

Note that IGNORECASE = 1 is a gnu awk feature and if you want a POSIX compliant way then use:

awk -v s="$site" 'tolower($0) ~ tolower(s)' sites.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM