计算 C 源代码中忽略注释和空行的行数

标签 c linux shell line-count

我想计算没有评论的行。

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/

相关文章:

c - 如何在使用 C 时找出 Linux 中的剩余堆栈

shell - 用制表符替换所有前 4 个空格

c - 在 C 中使用 fork() 调用时程序进入无限循环

c - 内存泄漏

linux - sed 无法使用 bash 脚本注释文件中的一行

c - 使用 nohup 或 setsid 逃避 alarm() 进程超时?

c - 如何重新排序整数的字节?

c - 使用 scanf %m 的程序不可移植

linux - 如何使用sed命令删除没有备份文件的行?

linux - Bash while 循环意外停止