【问题标题】:File name printed twice when using wc使用 wc 时文件名打印两次
【发布时间】:2012-05-30 14:12:54
【问题描述】:

为了打印当前文件夹的所有“.txt”文件中的行数,我使用以下脚本:

for f in *.txt;
do l="$(wc -l "$f")";
echo "$f" has "$l" lines;
done 

但在输出中我得到:

lol.txt has 2 lol.txt lines

为什么lol.txt 会打印两次(尤其是在 2 次之后)?我想需要某种流刷新,但我不知道在这种情况下如何实现。所以我应该在脚本中进行哪些更改以获取输出:

lol.txt has 2 lines

【问题讨论】:

  • 如果你只是从命令行运行wc -lol.txt,那么发生的事情应该很明显

标签: linux shell wc


【解决方案1】:

您可以使用 'cut' 删除文件名:

for f in *.txt;
do l="$(wc -l "$f" | cut -f1 -d' ')";
echo "$f" has "$l" lines;
done 

【讨论】:

    【解决方案2】:

    文件名被打印两次,因为wc -l "$f" 也在行数之后打印文件名。尝试将其更改为cat "$f" | wc -l。

    【讨论】:

    • 或使用read读取号码:wc -l /etc/passwd | { read n rest ; echo $n ; }
    • 没有,但更可靠一点。可能有一个 wc 在从 stdin 读取时打印 /dev/stdin 而不是什么都没有。
    • 我还没有遇到过这样的wc,但我想是有可能的。
    • 来自pubs.opengroup.org/onlinepubs/9699919799/utilities/wc.html: If no input file operands are specified, no name shall be written and no <blank> characters preceding the pathname shall be written.
    【解决方案3】:

    wc 打印文件名,因此您可以将脚本编写为:

    ls *.txt | while read f; do wc -l "$f"; done
    

    或者,如果你真的想要详细的输出,试试

    ls *.txt | while read f; do wc -l "$f" | awk '{print $2, "has", $1, "lines"}'; done
    

    【讨论】:

      【解决方案4】:

      这里有个窍门。让 wc 读取标准输入,它不会打印文件名:

      for f in *.txt; do
          l=$(wc -l < "$f")
          echo "$f" has "$l" lines
      done
      

      【讨论】:

      • (1) l=$(wc -l
      • 使用重定向后,wc 没有得到文件名,wc 专门处理这种情况,只输出计数
      猜你喜欢
      • 2012-05-01
      • 1970-01-01
      • 2012-01-17
      • 1970-01-01
      • 1970-01-01
      • 2011-07-20
      • 1970-01-01
      • 2017-08-26
      • 2014-02-16
      相关资源
      最近更新 更多