我想检查文件是否被超过 50% 的 javascript 风格注释注释掉//
。我的想法是计算文件中的行数,然后计算行数//
并做一些简单的数学运算。
如果有人使用多行注释,那就很棘手了/* ... */
有什么更好的方法来解决这个问题?
答案1
看看这个 shell 脚本是否适合你:
#!/bin/bash
if [ $# -eq 0 ]; then
echo "You have to specify a file. Exiting..."
exit 1
fi
if [ ! -r $1 ]; then
echo "File '$1' doesn't exist or is not readable. Exiting..."
exit
fi
# count every line
lines=$(wc -l $1 | awk '{print $1}')
echo "$lines total lines."
# count '//' comments
commentType1=$(sed -ne '/^[[:space:]]*\/\//p' $1 | wc -l | awk '{print $1}')
echo "$commentType1 lines contain '//' comments."
# count single line block comments
commentType2=$(sed -ne '/^[[:space:]]*\/\*.*\*\/[[:space:]]*/p' $1 | wc -l)
echo "$commentType2 single line block comments"
# write code into temporary file because we need to tamper with the code
tmpFile=/tmp/$(date +%s%N)
cp $1 $tmpFile
# remove single line block comments
sed -ie '/^[[:space:]]*\/\*.*\*\/[[:space:]]*/d' $tmpFile
# count multiline block comments
commentType3=$(sed -ne ':start /^[[:space:]]*\/\*/!{n;bstart};p; :a n;/\*\//!{p;ba}; p' $tmpFile | wc -l | awk '{print $1}')
echo "$commentType3 of lines belong to block comments."
percent=$(echo "scale=2;($commentType1 + $commentType2 + $commentType3) / $lines * 100" | bc -l)
echo "$percent% of lines are comments"