微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

bash – wc作为变量的结果

我想使用来自“wc”的行作为变量。例如:
echo 'foo bar' > file.txt
echo 'blah blah blah' >> file.txt
wc file.txt

2  5 23 file.txt

我想要像$ lines,$ words和$ characters与值2,5和23相关联的东西。如何在bash中这样做?

还有其他解决方案,但是我通常使用的一个简单的方法是将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

这种方法的优点是您不需要为每个变量创建一些awk进程。缺点是你需要一个临时文件,你应该删除它。

小心:这不行:

wc file.txt | read lines words characters filename

问题是要读取的管道创建另一个进程,并且变量在那里被更新,所以它们在调用shell中是不可访问的。

编辑:添加解决方案由arnaud576875:

read lines words chars filename <<< $(wc x)

在不写入文件的情况下工作(并且没有管道问题)。这是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.

关键是“词扩展”位。

原文地址:https://www.jb51.cc/bash/387638.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐