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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2451635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 21:49:14  来源:igfitidea点击:

Howto Pass A String as Parameter in AWK within Bash Script

linuxbashunixawk

提问by neversaint

I have a text file which I want to filter using awk. The text file looks like this:

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

foo 1
bar 2
bar 0.3
bar 100
qux 1033

I want to filter those files with awk inside a bash script.

我想在 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=
col1type="foo"   

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

But somehow it failed. What's the right way to do it?

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

采纳答案by John Kugelman

You need double quotes to allow variable interpolation, which means you then need to escape the other dollar signs with backslashes so $1and $2are notinterpolated. Also you need double quotes around "$col1type".

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

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

回答by ghostdog74

pass it in using -voption of awk. that way, you separate out awk variables and shell variables. Its neater also without extra quoting.

使用-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=
col1type="foo"   

#Filters
awk -vcoltype="$col1type" '>0 && ==col1type' $input

回答by sudhakar

"double quote single quote"

“双引号单引号”

awk '{print "''"}'


example:


例子:

$./a.sh arg1 
arg1



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



linux tested

linux 测试

回答by Ignacio Vazquez-Abrams

Single quotes inhibit variable expansion in bash:

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

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