我想在没有评论的情况下计算行数。
cat `find linux-4.10.2 -name "*.c" -print` | wc -l
这计算 .c 文件中的行数
cpp -fpreprocessed -dD -P fork.c
这删除评论
grep "^\s*$" fork.c
这计数空行
如何编写命令来计算代码行数并清空行数?
我想在没有评论的情况下计算行数。
cat `find linux-4.10.2 -name "*.c" -print` | wc -l
这计算 .c 文件中的行数
cpp -fpreprocessed -dD -P fork.c
这删除评论
grep "^\s*$" fork.c
这计数空行
如何编写命令来计算代码行数并清空行数?
你可以应用这样的东西:
while IFS= read -r -d '' fl;do
#your commands here
echo "total lines= $(wc -l <$fl)"
echo "lines without comments= $(wc -l < <(cpp -fpreprocessed -dD -P $fl))"
#Considering that above cpp will return all the lines without the comments.
#more commands
done< <(find linux-4.10.2 -type f -name "*.c" -print0)
PS:我们在 find 中使用 -print0 ,将 null 作为文件名分隔符,并确保所有文件名都将被 while read 循环正确处理,无论它们是否包含特殊字符、空格等
PS2:如果您建议注释行的外观,我们也可以使用 sed 等其他工具将其删除。请参阅此示例:
$ a=$'code\n/*comment1\ncooment2\ncomment3*/\ncode'
$ echo "$a"
code
/*comment1
cooment2
comment3*/
code
$ wc -l <<<"$a"
5
$ sed '/\/\*/,/\*\//d' <<<"$a" #for variables you need <<<, for files just one <
code
code
$ wc -l < <(sed '/\/\*/,/\*\//d' <<<"$a")
2