如何在Bash脚本中将字符串作为AWK中的参数传递

nev*_*int 5 unix linux bash awk

我有一个文本文件,我想用awk过滤.文本文件如下所示:

foo 1
bar 2
bar 0.3
bar 100
qux 1033
Run Code Online (Sandbox Code Playgroud)

我想在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
Run Code Online (Sandbox Code Playgroud)

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

gho*_*g74 10

使用-v选项传递给它awk.这样,你分离出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
Run Code Online (Sandbox Code Playgroud)


Joh*_*ica 5

你需要双引号允许变量替换,这意味着你需要再逃避反斜杠所以对方美元符号$1,并$2插。此外,您还需要双引号"$col1type"

awk "\$2>0 && \$1==\"$col1type\"" 
Run Code Online (Sandbox Code Playgroud)


sud*_*kar 5

"双引号单引号"

awk '{print "'$1'"}'
Run Code Online (Sandbox Code Playgroud)


例:

$./a.sh arg1 
arg1
Run Code Online (Sandbox Code Playgroud)


$cat a.sh 
echo "test" | awk '{print "'$1'"}'
Run Code Online (Sandbox Code Playgroud)


linux测试过