14

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

threshold = $1

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

5 blargh
6 tree
2 dog
1 fox
9 fridge

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

我目前正在使用:

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

但没有打印出来,我们将不胜感激。

4

1 回答 1

31

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

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

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

编辑:

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

$1 > threshold { print }

这行得通,但`print 不是必需的(这是默认操作),这就是为什么我将它缩短为

$1 > threshold
于 2013-11-05T23:47:59.167 回答