2010-03-16 57 views
4

我有一个文本文件,我想用awk过滤 。该文本文件看起来像这样:Howto在Bash脚本中将字符串作为参数传递给AWK

foo 1 
bar 2 
bar 0.3 
bar 100 
qux 1033 

我想用awk在bash脚本中过滤这些文件。

#!/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 

但不知何故,它失败了。什么是正确的做法?

回答

4

你需要双引号允许变量替换,这意味着,你需要转义反斜线其他美元符号等等$1$2插值。你还需要双引号"$col1type"

awk "\$2>0 && \$1==\"$col1type\"" 
+0

谢谢你,谢谢yoooou :))......你不知道多少走上找到这样的答案......再次谢谢主席先生 – 2014-08-05 19:48:17

2

单引号抑制在bash变量扩展:

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

传中使用的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 
+0

的“ - v'符号符合POSIX标准;旧的(System V-ish)版本的awk也可以在没有'-v'选项的情况下允许'parameter = value'。最好是明确的 - 使用'-v',除非你的系统有问题。 – 2010-03-16 02:02:18

+0

如果确实使用'parameter = value'语法(不带'-v'前缀),它必须在$'> 0 ...'和'$ input'参数之间。但是我怀疑现在有很多不接受'-v'的系统,最好在可能的时候使用它。此外,John Kugelman的回答说这种方法更强大一点:如果coltype的值为'xyz {next} {print“garbage”}',该怎么办? – dubiousjim 2012-04-19 01:16:01

5

“双引号单引号”

awk '{print "'$1'"}' 


例如:

$./a.sh arg1 
arg1 


$cat a.sh 
echo "test" | awk '{print "'$1'"}' 


Linux的测试

相关问题