【问题标题】:Get and process the last word of each line while looping through lines of text在遍历文本行时获取并处理每行的最后一个单词
【发布时间】:2016-09-09 04:39:37
【问题描述】:

所以,假设我有这个数据文件:

apples   asd   45      321     7000
oranges   gl   78      102     850
some    ltd     83      15      500
other   nova    80      50      3500
stuff    600     65      115     450

我想遍历每一行,得到最后一个字(这是大数字),这应该是价格。然后检查它是否小于1000,如果是 - 将其输出到另一个文件。

这是我得到的:

touch items_cheaper_than_1k.txt
while read LINE
do
        PRICE="$(cut -d. -f3 $LINE)"
        if [$PRICE < 1000]; then
                $LINE >> items_cheaper_than_1k.txt
        fi
done < cars.txt
cat items_cheaper_than_1k.txt

问题是我得到了错误

cut: apples: No such file or directory
cut: asd: No such file or directory
cut: 45: No such file or directory
cut: 321: No such file or directory
cut: 7000: No such file or directory

(并按顺序为每行的每个单词)。我剪错了吗?

在每行错误列表之后,我得到line 5: 1000]: No such file or directory

【问题讨论】:

  • cut 的参数是文件名,而不是要处理的字符串。您需要将字符串通过管道传输到cut
  • 你还需要学习基本的shell语法。 if [$PRICE &lt; 1000] 应该是 if [ $PRICE -lt 1000 ][] 周围需要空格,您必须使用 -lt,因为 &lt; 是 shell 的输入重定向运算符。而$LINE &gt;&gt; 应该是echo $LINE &gt;&gt;

标签: bash


【解决方案1】:

awk:

awk '$NF<1000' file.txt

$NF 是最后一个字段的值,$NF&lt;1000 检查该值是否小于 1000,如果是则打印该行。

将输出保存在另一个文件中,例如out.txt:

awk '$NF<1000' file.txt >out.txt

示例:

% cat file.txt 
apples   asd   45      321     7000
oranges   gl   78      102     850
some    ltd     83      15      500
other   nova    80      50      3500
stuff    600     65      115     450

% awk '$NF<1000' file.txt
oranges   gl   78      102     850
some    ltd     83      15      500
stuff    600     65      115     450

【讨论】:

  • LOL,这比我编写整个脚本的方法要容易和快 9999 倍!知道命令的力量...
  • @Milkncookiez 是的。 awk 是任何字段分隔数据的 go-to 工具。
猜你喜欢
  • 2017-07-22
  • 2020-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-12
  • 1970-01-01
  • 2013-11-25
相关资源
最近更新 更多