简体   繁体   English

AWK-如何使用命令行参数($ 1)进行过滤

[英]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. 我正在寻找的是用命令行参数($ 1)替换单词“ EASYDOC”,以便以“ myScript.sh EASYDOC”的身份执行,而lettin EASYDOC替换了awk行的模式变量引用。

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 : 首先,要将shell变量传递到awk脚本中,请使用-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 : 其次,除了字符串常量外,您将无法对其他任何表达式使用正则表达式/.../语法,因此请将~运算符与$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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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