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

u4dcyp6a  于 2024-01-07  发布在  Unix
关注(0)|答案(5)|浏览(380)

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

y3bcpkx1

y3bcpkx11#

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

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

字符串

xwbd5t1u

xwbd5t1u2#

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

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

字符串
或者这个awk:

  1. awk 'END{print NR}' file

eoigrqb6

eoigrqb63#

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

  1. awk '1' file | wc -l

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

示例

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

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


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

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


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

展开查看全部
izj3ouym

izj3ouym4#

尊重

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

Line Count函数

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

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

字符串

不带函数计算行数

  1. # Line count of the file
  2. $ cat file_with_newline | wc -l
  3. 3
  4. # Line count of the file
  5. $ cat file_without_newline | wc -l
  6. 2
  7. # Line count of the file unchanged by cat
  8. $ cat file_without_newline | cat | wc -l
  9. 2
  10. # Line count of the file changed by awk
  11. $ cat file_without_newline | awk 1 | wc -l
  12. 3
  13. # Line count of the file changed by only the first call to awk
  14. $ cat file_without_newline | awk 1 | awk 1 | awk 1 | wc -l
  15. 3
  16. # Line count of the file unchanged by awk because it ends with a newline character
  17. $ cat file_with_newline | awk 1 | awk 1 | awk 1 | wc -l
  18. 3

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

  1. # Character count of the file
  2. $ cat file_with_newline | wc -c
  3. 6
  4. # Character count of the file unchanged by awk because it ends with a newline character
  5. $ cat file_with_newline | awk 1 | awk 1 | awk 1 | wc -c
  6. 6
  7. # Character count of the file
  8. $ cat file_without_newline | wc -c
  9. 5
  10. # Character count of the file changed by awk
  11. $ cat file_without_newline | awk 1 | wc -c
  12. 6

使用函数计算行数

  1. # Line count function used on stdin
  2. $ cat file_with_newline | wcl
  3. 3
  4. # Line count function used on stdin
  5. $ cat file_without_newline | wcl
  6. 3
  7. # Line count function used on filenames passed as arguments
  8. $ wcl file_without_newline file_with_newline
  9. 3
  10. 3

展开查看全部
5fjcxozz

5fjcxozz5#

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

  1. from man page of wc
  2. -l, --lines
  3. print the newline counts

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

  1. grep -c '^' filename

相关问题