nlarralde
nlarralde

Reputation: 37

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.

Upvotes: 0

Views: 546

Answers (1)

jas
jas

Reputation: 10865

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 }'

E.g:

$ 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

Upvotes: 2

Related Questions