bash awk 的 $1 与 shell 脚本中的 $1 冲突

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9553317/
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-18 01:43:15  来源:igfitidea点击:

awk's $1 conflicts with $1 in shell script

bashshellawk

提问by James Bond

I am writting a shell script which includes a couple of awk lines

我正在编写一个包含几行 awk 的 shell 脚本

the awk line looks like:

awk 行看起来像:

cat input.csv | awk -F, '~// {print "is good"}'

the first $1is the first column of the input csv, the second $1is supposed to be the first command line input of this shell script

第一个$1是输入csv的第一列,第二个$1应该是这个shell脚本的第一个命令行输入

I tried to put a \in front of the second $, but it seems to be not working.

我试图将 a\放在第二个前面$,但似乎不起作用。

Can anyone help?

任何人都可以帮忙吗?

回答by Adrian Pronk

cat input.csv | awk -F, '~/'""'/ {print "is good"}'

You need to close the 'string, insert the shell $1(inside "in case there are special characters), then reopen the 'string.

您需要关闭'字符串,插入外壳$1(内部"以防有特殊字符),然后重新打开'字符串。

And you may want to check whether the $1from shell contains /characters which will upset the regular expression.

并且您可能想要检查$1from shell是否包含/会扰乱正则表达式的字符。

And as @Ignacio Vazquez-Abrams indicated, you don't need to pipe the output of catto awk, you can just get awkto read the file directly. That is:

正如@Ignacio Vazquez-Abrams 所指出的,您不需要将 的输出通过管道cat传输到 awk,您只需awk直接读取文件即可。那是:

cat input.csv | awk ...

can be simplified to:

可以简化为:

awk ... < input.csv

回答by Ignacio Vazquez-Abrams

A variable is fine too.

一个变量也很好。

awk -F, -v needle="" ' ~ needle {print "is good"}' < input.csv

回答by jlliagre

cat or a redirection isn't needed. Here is a third variant using backslash:

cat 或不需要重定向。这是使用反斜杠的第三种变体:

awk -F, "$1~// {print \"is good\"}" input.csv