Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 如何在Bash脚本中以参数形式在AWK中传递字符串_Linux_Bash_Unix_Awk - Fatal编程技术网

Linux 如何在Bash脚本中以参数形式在AWK中传递字符串

Linux 如何在Bash脚本中以参数形式在AWK中传递字符串,linux,bash,unix,awk,Linux,Bash,Unix,Awk,我有一个要筛选的文本文件 使用awk。文本文件如下所示: foo 1 bar 2 bar 0.3 bar 100 qux 1033 我想在bash脚本中使用awk过滤这些文件 #!/bin/bash #input file input=myfile.txt # I need to pass this as parameter # cos later I want to make it more general like # coltype=$1 col1type="foo" #Fi

我有一个要筛选的文本文件 使用awk。文本文件如下所示:

foo 1
bar 2
bar 0.3
bar 100
qux 1033
我想在bash脚本中使用awk过滤这些文件

#!/bin/bash

#input file
input=myfile.txt

# I need to pass this as parameter
# cos later I want to make it more general like
# coltype=$1
col1type="foo"   

#Filters
awk '$2>0 && $1==$col1type' $input

但不知怎的,它失败了。正确的方法是什么?

单引号禁止bash中的变量扩展:

awk '$2>0 && $1=='"$col1type"

您需要双引号来允许变量插值,这意味着您需要用反斜杠转义其他美元符号,以便不插值
$1
$2
。您还需要在“$col1type”周围加上双引号


使用
awk
-v
选项将其传入。这样,您就可以分离出awk变量和shell变量。它也更整洁,没有额外的报价

#!/bin/bash

#input file
input=myfile.txt

# I need to pass this as parameter
# cos later I want to make it more general like
# coltype=$1
col1type="foo"   

#Filters
awk -vcoltype="$col1type" '$2>0 && $1==col1type' $input
“双引号单引号”


例子:




linux测试

v符号与POSIX兼容;awk的较旧(系统V-ish)版本也可能允许
parameter=value
而不使用“-V”选项。最好是显式的-除非系统上有问题,否则使用“-v”。如果使用裸
参数=值
语法(没有
-v
前缀),它必须介于
'$2>0…
$input
参数之间。但我怀疑还有很多系统不再接受
-v
,最好在可能的情况下使用它。此外,这个方法比John Kugelman的答案更健壮:如果coltype持有值
xyz{next}{print“garbage”}
,那该怎么办?谢谢!我是个新手,花了好几个小时研究如何简单地将shell变量字符串导入(有点复杂的)awk表达式。
#!/bin/bash

#input file
input=myfile.txt

# I need to pass this as parameter
# cos later I want to make it more general like
# coltype=$1
col1type="foo"   

#Filters
awk -vcoltype="$col1type" '$2>0 && $1==col1type' $input
awk '{print "'$1'"}'
$./a.sh arg1 
arg1
$cat a.sh 
echo "test" | awk '{print "'$1'"}'