bash 文件中行数的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9458752/
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-18 01:39:41  来源:igfitidea点击:

Variable for number of lines in a file

bashunix

提问by JA3N

I'm trying to put the number of lines in a file into an integer variable.

我试图将文件中的行数放入一个整数变量中。

This is how i'm doing it

这就是我的做法

typeset -i x
x=`wc -l `

where $1 is the command line arg

其中 $1 是命令行参数

The problem is that wc -l gives a number and the filename like: 5 blah

问题是 wc -l 给出了一个数字和文件名,如:5 blah

Is there a way to only put the number into x?

有没有办法只将数字放入 x 中?

回答by Oliver Charlesworth

You could do cat $1 | wc -linstead.

你可以这样做cat $1 | wc -l

Or wc -l $1 | cut -d " " -f 1.

或者wc -l $1 | cut -d " " -f 1

回答by l0b0

x=$(wc -l < "")

This avoids a useless use of catand any forks, and would work on a path containing spaces and even newlines.

这避免了无用的使用cat和任何分叉,并且可以在包含空格甚至换行符的路径上工作。

回答by Selman Ulug

wc -l  | awk '{print }'

with awk

用 awk

回答by mVChr

Or with sed...

或与sed...

wc -l  | sed 's/^ *\([0-9]*\).*$//'

Or, assuming the first space is the one after the number:

或者,假设第一个空格是数字之后的空格:

wc -l  | sed 's/ .*$//'

回答by jfg956

You can use the shell to remove the file name. This has the advantage of not starting a 2nd process as cat, cut, sedor awk:

您可以使用 shell 删除文件名。这还没有开始第二过程的优势catcutsedawk

var=$(wc -l _your_file_)
nb_lines=${var%% *}

You can also rewrite nb_lines=${var%% *}with nb_lines=${var/ */}, but the 2nd form is less portable beingbash` specific.

您也可以nb_lines=${var%% *}使用nb_lines=${var/ */}, but the 2nd form is less portable beingbash` 特定的重写。

Update

更新

I read above that some wc's output start with spaces, so the above can be rewritten:

我在上面读到 somewc的输出以空格开头,因此可以重写上面的内容:

#var=$(wc -l _your_file_)
var="   3    file"
var=$(echo $var)
nb_lines=${var%% *}

Using echoto get rid of the extra spaces.

使用echo摆脱多余的空格。

回答by CrackNRock

In case you are trying to put line numbers in the file i recommend.

如果您尝试将行号放入我推荐的文件中。

In windows:

在窗口中:

awk '{print NR " " $s}' filename > ouputfile

In Linux:

在 Linux 中:

cat -n file > outputfile

I segregated them because in windows one cannot run cat -nso had to use awk.

我将它们分开是因为在 Windows 中无法运行,cat -n所以不得不使用 awk。

回答by pedram bashiri

filename='test.txt'
line_no=$(cat ${filename} | wc -l)
echo ${line_no}