unix wc -l不计算最后一个文件,如果它没有行结束符

u4dcyp6a  于 4个月前  发布在  Unix
关注(0)|答案(5)|浏览(65)

我需要计算一个unix文件的所有行数。这个文件有3行,但是wc -l只给了2行。
我知道它不计算最后一行,因为它没有行尾字符
有没有人能告诉我如何计算这条线?

y3bcpkx1

y3bcpkx11#

grep -c返回匹配行数。只需使用空字符串""作为匹配表达式:

$ echo -n $'a\nb\nc' > 2or3.txt
$ cat 2or3.txt | wc -l
2
$ grep -c "" 2or3.txt
3

字符串

xwbd5t1u

xwbd5t1u2#

在Unix文件中,最好所有行都以EOL \n结尾。你可以这样做:

{ cat file; echo ''; } | wc -l

字符串
或者这个awk:

awk 'END{print NR}' file

eoigrqb6

eoigrqb63#

这种方法将给予正确的行数,而不管文件中的最后一行是否以换行符结束。
awk将确保在其输出中,它打印的每一行都以一个新行字符结束。因此,要确保每一行在发送到wc之前都以一个新行结束,用途:

awk '1' file | wc -l

字符串
在这里,我们使用的是一个简单的awk程序,它只包含数字1awk将这个神秘的语句解释为“打印该行”,它确实这样做了,并确保存在一个尾随的换行符。

示例

让我们创建一个包含三行的文件,每行以一个换行符结束,并计算行数:

$ echo -n $'a\nb\nc\n' >file
$ awk '1' f | wc -l
3


找到正确的号码。
现在,让我们再试一次,最后一行缺失:

$ echo -n $'a\nb\nc' >file
$ awk '1' f | wc -l
3


awk会自动更正丢失的换行符,但如果最后一个换行符存在,则不处理文件。

izj3ouym

izj3ouym4#

尊重

我尊重answer from John1024,并希望扩大它。

Line Count函数

我发现自己比较了很多行计数,特别是从剪贴板,所以我已经定义了一个bash函数。我想修改它,以显示文件名,当传递超过1个文件的总数。然而,它还没有足够重要,我这样做到目前为止。

# semicolons used because this is a condensed to 1 line in my ~/.bash_profile
function wcl(){
  if [[ -z "${1:-}" ]]; then
    set -- /dev/stdin "$@";
  fi;
  for f in "$@"; do
    awk 1 "$f" | wc -l;
  done;
}

字符串

不带函数计算行数

# Line count of the file
$ cat file_with_newline    | wc -l
       3

# Line count of the file
$ cat file_without_newline | wc -l
       2

# Line count of the file unchanged by cat
$ cat file_without_newline | cat | wc -l
       2

# Line count of the file changed by awk
$ cat file_without_newline | awk 1 | wc -l
       3

# Line count of the file changed by only the first call to awk
$ cat file_without_newline | awk 1 | awk 1 | awk 1 | wc -l
       3

# Line count of the file unchanged by awk because it ends with a newline character
$ cat file_with_newline    | awk 1 | awk 1 | awk 1 | wc -l
       3

计数字符(为什么不想在wc周围放置 Package 器)

# Character count of the file
$ cat file_with_newline    | wc -c
       6

# Character count of the file unchanged by awk because it ends with a newline character
$ cat file_with_newline    | awk 1 | awk 1 | awk 1 | wc -c
       6

# Character count of the file
$ cat file_without_newline | wc -c
       5

# Character count of the file changed by awk
$ cat file_without_newline | awk 1 | wc -c
       6

使用函数计算行数

# Line count function used on stdin
$ cat file_with_newline    | wcl
       3

# Line count function used on stdin
$ cat file_without_newline | wcl
       3

# Line count function used on filenames passed as arguments
$ wcl file_without_newline  file_with_newline
       3
       3

5fjcxozz

5fjcxozz5#

“wc -l”不计算文件行数。
它计算'\n'(换行符)的计数。

from man page of wc

 -l, --lines
              print the newline counts

字符串
你应该使用grep -c '^'来获取行数。

grep -c '^' filename

相关问题