Regular-Expression

獲取被註釋掉的 javascript 文件的百分比

  • September 9, 2020

我想檢查文件是否超過 50% 被//. 我的想法是計算文件中的行數,然後計算數量//並做一些簡單的數學運算。

但是,如果有人使用多行註釋會很棘手/* ... */

有什麼更好的方法來解決這個問題?

看看這個 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"

引用自:https://unix.stackexchange.com/questions/608201