我有这个文件
a b c d e 1
b c s d e 1
a b d e f 2
d f g h j 2
Run Code Online (Sandbox Code Playgroud)
awk 'if $6==$variable {print @0}' myfile
Run Code Online (Sandbox Code Playgroud)
如何在shell脚本中使用此代码,$variable在命令提示符下由用户获取参数?
您可以使用awk的-v标志.而且由于awk默认打印,您可以尝试例如:
variable=1
awk -v var=$variable '$6 == var' file.txt
Run Code Online (Sandbox Code Playgroud)
结果:
a b c d e 1
b c s d e 1
Run Code Online (Sandbox Code Playgroud)
编辑:
该命令基本相同,包含在shell中.您可以在具有多个这样的参数的shell脚本中使用它script.sh 2 j
内容script.sh:
command=$(awk -v var_one=$1 -v var_two=$2 '$6 == var_one && $5 == var_two' file.txt)
echo -e "$command"
Run Code Online (Sandbox Code Playgroud)
结果:
d f g h j 2
Run Code Online (Sandbox Code Playgroud)