我有一个包含以下行的脚本:
RHEL7.5> cat myScript.sh
...
awk -F":" '/^(EASYDOC)+/ {print $2}' /etc/oratab
...
RHEL7.5>
我正在寻找的是用命令行参数($ 1)替换单词“EASYDOC”,以便执行“myScript.sh EASYDOC”并让let EASYDOC替换awk行的模式变量引用。
例如:
awk -F":" '/^(something lets recognize $1 as arg)+/ {print $2}' /etc/oratab
是可取的。提前致谢。内斯托尔。
首先,要将shell变量传递给awk脚本,请使用-v
:
awk -F":" -v arg="$1" ...
其次,除了字符串常量之外,您将无法使用正则表达式/.../
语法,因此请使用~
运算符和$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