awk与/bin/bash-c一起使用时不起作用
这正确打印 test
$ echo 'this is a test' | awk '{print $4}'
test
虽然在里面使用这个命令/bin/bash -c不起作用
/bin/bash -c "echo 'this is a test' | awk '{print $4}'"
this is a test
使用 with 时如何让 awk 正常工作/bin/bash -c?
回答
$4 由 shell 消耗,因为您有双引号命令字符串。
您可以通过-x在bash命令行中添加来检查跟踪输出:
bash -xc "echo 'this is a test' | awk '{print $4}'"
+ echo 'this is a test'
+ awk '{print }'
this is a test
由于$4扩展为空字符串,它有效地运行awk '{print }',因此在输出中打印完整的行。
要解决此问题,您应该使用转义符$来避免这种扩展:
bash -c "echo 'this is a test' | awk '{print $4}'"
test