bash – wc作为变量的结果
发布时间:2020-12-15 19:12:13 所属栏目:安全 来源:网络整理
导读:我想使用来自“wc”的行作为变量。例如: echo 'foo bar' file.txtecho 'blah blah blah' file.txtwc file.txt2 5 23 file.txt 我想要像$ lines,$ words和$ characters与值2,5和23相关联的东西。如何在bash中这样做? 还有其他解决方案,但是我通常使用的一
我想使用来自“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. 关键是“词扩展”位。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |