2010-03-16 58 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的測試

相關問題