我想计算没有评论的行。
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
关于计算 C 源代码中忽略注释和空行的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42749566/