简体   繁体   中英

AWK - How to filter using a command line argument ($1)

I have a script with the following line:

RHEL7.5> cat myScript.sh
...
awk -F":" '/^(EASYDOC)+/ {print $2}' /etc/oratab
...
RHEL7.5>

What I'm looking for is to replace the word "EASYDOC" with a command line argument ($1) in order to execute as "myScript.sh EASYDOC" and lettin EASYDOC replaces the pattern variable reference at awk line.

For instance:

awk -F":" '/^(something lets recognize $1 as arg)+/ {print $2}' /etc/oratab

would be desirable. Thanks in advance. Néstor.

First, to pass a shell variable into your awk script, use -v :

awk -F":" -v arg="$1" ...

Second, you won't be able to use the regex /.../ syntax for anything but a string constant, so instead use the ~ operator with $0 :

awk -F":" -v arg="$1" '$0 ~ "^(something lets recognize " arg " as arg)+" { print $2 }'

Eg:

$ var=foo

$ cat file
something lets recognize foo as arg:shut the door:the color is red

$ awk -F":" -v arg=$var '$0 ~ "^(something lets recognize " arg " as arg)+" { print $2 }' file
shut the door

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