如何在运行时显示行数?

时间:2017-03-19 15:42:26

标签: bash sh wc

“在文件中附加以下命令:当执行此文件时,它将执行以下操作:

4)显示此文件有x行

5)显示此文件有x个单词

6)显示此文件有x个字节 “

我知道命令是wc的变种,但我无法弄清楚如何将该命令添加到脚本中,只知道如何运行它。

2 个答案:

答案 0 :(得分:0)

lines=$(wc -l $0)
echo This file has $lines lines
words=$(wc -w $0)
echo This file has $words words
bytes=$(wc -b $0)
echo This file has $bytes bytes

应该这样做。

答案 1 :(得分:0)

这是一个单行,使用bash process substitution

$ read lines words bytes filename < <(wc /path/to/file)

输出也是一个单行,如果你愿意,你可以利用bash数组。这是一个真实的例子:

$ read -a arr < <(wc /etc/passwd);
$ declare -p arr
declare -a arr=([0]="96" [1]="265" [2]="5925" [3]="/etc/passwd")
$ unset arr[3]
$ printf 'lines: %d\nwords: %d\nbytes: %d\n' "${arr[@]}"
lines: 96
words: 265
bytes: 5925

使用临时文件可以实现POSIX shell中的类似结果:

$ tmp=$(mktemp /tmp/foo.XXXX)
$ wc /etc/passwd > $tmp
$ read lines words bytes filename < $tmp
$ rm $tmp
$ printf 'lines: %d\nwords: %d\nbytes: %d\n' "$lines" "$words" "$bytes"
lines: 96
words: 265
bytes: 5925

或者您可以在没有临时文件的情况下将数据作为here-doc获取:

$ read lines words bytes filename <<EOT
> $(wc /etc/passwd)
> EOT

(显然,如果您要编写此脚本,则会删除交互式提示。)

请注意printf推荐输出echo,因为它在不同的操作系统和shell中是一致的。 This excellent post解释了一些注意事项。