wc作为变量的结果

719*_*016 27 bash shell wc

我想使用来自'wc'的行作为变量.例如:

echo 'foo bar' > file.txt
echo 'blah blah blah' >> file.txt
wc file.txt

2  5 23 file.txt
Run Code Online (Sandbox Code Playgroud)

我想有这样的事情$lines,$words以及$characters相关的价值观2,523.我怎么能用bash做到这一点?

Arn*_*anc 40

纯粹的bash :(没有awk)

a=($(wc file.txt))
lines=${a[0]}
words=${a[1]}
chars=${a[2]}
Run Code Online (Sandbox Code Playgroud)

这通过使用bash的数组来工作.a=(1 2 3)创建一个包含元素1,2和3的数组.然后我们可以使用${a[indice]}语法访问单独的元素.

替代方案:(基于有价值的解决方案)

read lines words chars <<< $(wc x)
Run Code Online (Sandbox Code Playgroud)

或者在sh:

a=$(wc file.txt)
lines=$(echo $a|cut -d' ' -f1)
words=$(echo $a|cut -d' ' -f2)
chars=$(echo $a|cut -d' ' -f3)
Run Code Online (Sandbox Code Playgroud)


dan*_*ast 13

还有其他解决方案,但我通常使用的一个简单方法是将输出wc放在一个临时文件中,然后从那里读取:

wc file.txt > xxx
read lines words characters filename < xxx 
echo "lines=$lines words=$words characters=$characters filename=$filename"
lines=2 words=5 characters=23 filename=file.txt
Run Code Online (Sandbox Code Playgroud)

此方法的优点是您不需要awk为每个变量创建多个进程.缺点是你需要一个临时文件,之后你应该删除它.

小心:这不起作用:

wc file.txt | read lines words characters filename
Run Code Online (Sandbox Code Playgroud)

问题是管道read创建另一个进程,并且变量在那里更新,因此在调用shell中无法访问它们.

编辑:通过arnaud576875添加解决方案:

read lines words chars filename <<< $(wc x)
Run Code Online (Sandbox Code Playgroud)

无需写入文件即可工作(并且没有管道问题).这是特定的bash.

从bash手册:

Here Strings

   A variant of here documents, the format is:

          <<<word

   The word is expanded and supplied to the command on its standard input.
Run Code Online (Sandbox Code Playgroud)

关键是"字扩展"位.

  • `read lines words chars <<< $(wc x)`无需写入文件即可工作(并且没有管道问题) (7认同)