我需要计算一个Unix文件中的所有行数。该文件有3行,但是wc -l
只给出了2行。
我知道这是因为它没有统计最后一行,因为它没有结束符。
请问有谁能告诉我如何将那一行也计入总行数?
grep -c
返回匹配行的数量。只需将空字符串 ""
用作匹配表达式:
grep -c
返回匹配行的数量。只需将空字符串 ""
用作匹配表达式:
$ echo -n $'a\nb\nc' > 2or3.txt
$ cat 2or3.txt | wc -l
2
$ grep -c "" 2or3.txt
3
-F
标志,grep解决方案的速度比最小的awk
或sed
版本要快得多,并且非常接近于wc -l
本身。 - Toby Speightripgrep
,使用 rg --fixed-strings --count ''
。 - HappyFace在Unix文件中,最好让所有行以EOL \n
结尾。你可以这样做:
{ cat file; echo ''; } | wc -l
或者使用这个awk:
awk 'END{print NR}' file
echo -n '' >> file
。 - anubhava{ cat file; echo ''; } | wc -l
- anubhavaawk 'END{print NR}' file
。 - anubhava\n
结尾,则{ cat file; echo ''; } | wc -l
会给出错误的答案,因为它总是会添加一个额外的行,因此基于awk的解决方案更好。 - PM 2Ring这种方法可以正确计算行数,无论文件中的最后一行是否以换行符结尾。
awk
会确保在其输出中,每个打印的行都以新行字符结尾。因此,在将行发送到 wc
之前,请确保每行都以换行符结尾:
awk '1' file | wc -l
$ 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
自动纠正缺少换行符的情况,但如果最后一个换行符存在,则保留文件不变。
我很尊重John1024的回答,并想对其进行扩展。
我经常比较行数,尤其是从剪贴板中复制出来的。因此,我定义了一个Bash函数。我想修改它以显示文件名,并在传递多个文件时显示总数。但是,这件事对我来说还不够重要。
# 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
周围添加包装器)# 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
from man page of wc
-l, --lines
print the newline counts
grep -c '^' filename