bash 打印字段编号大于 AWK 的行

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

Printing lines which have a field number greater than, in AWK

bashawk

提问by FatalError

I am writing a script in bash which takes a parameter and storing it;

我正在用 bash 编写一个脚本,它接受一个参数并存储它;

threshold = 

I then have sample data that looks something like:

然后我有看起来像这样的示例数据:

5 blargh
6 tree
2 dog
1 fox
9 fridge

I wish to print only the lines which have their number greater than the number which is entered as the parameter (threshold).

我希望仅打印其编号大于作为参数(阈值)输入的编号的行。

I am currently using:

我目前正在使用:

awk '{print  > $threshold}' ./file

But nothing prints out, help would be appreciated.

但没有打印出来,帮助将不胜感激。

回答by FatalError

You're close, but it needs to be more like this:

你很接近,但它需要更像这样:

$ threshold=3
$ awk -v threshold="$threshold" ' > threshold' file

Creating a variable with -vavoids the ugliness of trying to expand shell variables within an awkscript.

创建一个变量-v避免了在awk脚本中尝试扩展 shell 变量的丑陋。

EDIT:

编辑:

There are a few problems with the current code you've shown. The first is that your awkscript is single quoted (good), which stops $thresholdfrom expanding, and so the value is never inserted in your script. Second, your condition belongs outside the curly braces, which would make it:

您显示的当前代码存在一些问题。第一个是您的awk脚本是单引号(好),它停止$threshold扩展,因此该值永远不会插入到您的脚本中。其次,您的条件属于花括号之外,这将使它:

 > threshold { print }

This works, but the `print is not necessary (it's the default action), which is why I shortened it to

这有效,但不需要`print(这是默认操作),这就是为什么我将其缩短为

 > threshold