[英]How to get bash variables work on awk pipe
I can't get variable from my bash script to work on awk piping. 我无法从bash脚本获取变量以在awk管道上工作。
SERVER_PORT="27018"
...
HOLDER=`netstat -tlpn | awk -v sp=$SERVER_PORT '/:sp */ {split($NF,a,"/"); print a[1]}'`
After executing command for this variable next equation is TRUE! 执行此变量的命令后,下一个等式为TRUE!
...
if [ "$HOLDER" == "" ]; then
...
If I run 如果我跑
netstat -tlpn | awk '/:27018 */ {split($NF,a,"/"); print a[1]}'
on my shell window everything is fine and it gives me the PID of the process. 在我的shell窗口上,一切都很好,它为我提供了进程的PID。
So my question is: how to pass variable to awk correctly or something has broken? 所以我的问题是:如何正确地将变量传递给awk或发生故障? Running CentOS 7
运行CentOS 7
Inside a regular expression constant awk doesn't expand variables. 在正则表达式中,常量awk不会扩展变量。 So
/:sp */
is literally /:sp */
. 所以
/:sp */
实际上是/:sp */
。
You need to make that match a string: $0 ~ ":"sp" *"
您需要使该字符串匹配:
$0 ~ ":"sp" *"
awk scripts are made up of pattern {action}
pairs. awk脚本由
pattern {action}
对组成。 /:27018 */
is a pattern (using a regexp constant). /:27018 */
是一种模式(使用正则表达式常量)。 As I said at the beginning awk doesn't expand variables inside a regexp constant so /:sp */
is matching those literal characters. 正如我在开头所说,awk不会在 regexp常量内扩展变量,所以
/:sp */
匹配那些文字字符。
There are other patterns possible beyond a regexp constant. 除了正则表达式常量之外,还有其他模式可能。 Even static strings can be patterns (they are always true but they work).
甚至静态字符串也可以是模式(它们始终为true,但它们可以工作)。
~
is a regular expression match operator in awk. ~
是awk中的正则表达式匹配运算符。 You can use that to manually perform the same sort of match that the regexp constant pattern does. 您可以使用它来手动执行与regexp常量模式相同的匹配。
~
takes two string arguments. ~
需要两个字符串参数。
Putting that together we can match ( ~
) the whole line ( $0
) against a string constant regular expression (rather than a regexp constant) of ":"sp" *"
(the string ":"
, our variable sp
, and the string " *"
). 放在一起,我们可以将(
~
)整行( $0
)与":"sp" *"
(字符串":"
,我们的变量sp
和字符串)的字符串常量正则表达式(而不是regexp常量)匹配" *"
)。
Which, when put together, gets you (as I wrote above) $0 ~ ":"sp" *"
as the pattern instead of the regexp constant. 当它放在一起时,会让你(如上所述)
$0 ~ ":"sp" *"
作为模式而不是正则表达式常量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.