bash 将文本文件中的行数输出到 Unix 中的屏幕

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12731797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 22:47:05  来源:igfitidea点击:

Output number of lines in a text file to screen in Unix

bashunix

提问by Masterminder

Possible Duplicate:
bash echo number of lines of file given in a bash variable

可能的重复:
bash echo bash 变量中给出的文件行数

Was wondering how you output the number of lines in a text file to screen and then store it in a variable. I have a file called stats.txt and when I run wc -l stats.txtit outputs 8 stats.txt

想知道如何将文本文件中的行数输出到屏幕,然后将其存储在变量中。我有一个名为 stats.txt 的文件,当我运行wc -l stats.txt它时会输出8 stats.txt

I tried doing x = wc -l stats.txtthinking it would store the number only and the rest is just for visual but it does not work :(

我试着x = wc -l stats.txt认为它只会存储数字,其余的只是用于视觉,但它不起作用:(

Thanks for the help

谢谢您的帮助

回答by Janito Vaqueiro Ferreira Filho

There are two POSIX standard syntax for doing this:

有两种 POSIX 标准语法可以执行此操作:

x=`cat stats.txt | wc -l`

or

或者

x=$(cat stats.txt | wc -l)

They both run the program and replace the invocation in the script with the standard output of the command, in this case assigning it to the $xvariable. However, be aware that both trim ending newlines (this is actually what you want here, but can be dangerous sometimes, when you expect a newline).

它们都运行程序并用命令的标准输出替换脚本中的调用,在这种情况下将其分配给$x变量。但是,请注意,两者都修剪结束换行符(这实际上是您在这里想要的,但有时可能很危险,当您期望换行符时)。

Also, the second case can be easily nested (example: $(cat $(ls | head -n 1) | wc -l)). You can also do it with the first case, but it is more complex:

此外,第二种情况可以轻松嵌套(例如:)$(cat $(ls | head -n 1) | wc -l)。你也可以用第一种情况来做,但它更复杂:

`cat \`ls | head -n 1\` | wc -l`

There are also quotation issues. You can include these expressions inside double-quotes, but with the back-ticks, you must continue quoting inside the command, while using the parenthesis allows you to "start a new quoting" group:

还有报价问题。您可以将这些表达式包含在双引号内,但使用反引号,您必须在命令内继续引用,而使用括号允许您“开始一个新的引用”组:

"`echo \"My string\"`"
"$(echo "My string")"

Hope this helps =)

希望这会有所帮助 =)

回答by none

you may try:

你可以尝试:

x=`cat stats.txt | wc -l`

or (from the another.anon.coward's comment):

或(来自 another.anon.coward 的评论):

x=`wc -l < stats.txt`