我正在用 bash 编写一个脚本,它接受一个参数并存储它;
threshold = $1
然后我有看起来像这样的示例数据:
5 blargh
6 tree
2 dog
1 fox
9 fridge
我希望只打印编号大于作为参数(阈值)输入的编号的行。
我目前正在使用:
awk '{print $1 > $threshold}' ./file
但没有打印出来,将不胜感激。
最佳答案
你很接近,但它需要更像这样:
$ threshold=3
$ awk -v threshold="$threshold" '$1 > threshold' file
使用 -v
创建变量避免了在 awk
脚本中尝试扩展 shell 变量的丑陋行为。
编辑:
您显示的当前代码存在一些问题。第一个是您的 awk
脚本是单引号的(良好),这会阻止 $threshold
扩展,因此该值永远不会插入您的脚本中。其次,您的条件属于花括号之外,这将使它成为:
$1 > threshold { print }
这行得通,但 `print 不是必需的(这是默认操作),这就是为什么我将其缩短为
$1 > threshold
关于bash - 在 AWK 中打印字段编号大于的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19801358/