コメントアウトされたJavaScriptファイルの割合を取得します。

コメントアウトされたJavaScriptファイルの割合を取得します。

ファイルにJavaScriptスタイルのコメントが50%以上コメントアウトされていることを確認したいと思います//。私の考えは、ファイルの行数を数えてから行数を数え、//簡単な計算を実行することです。

誰かが複数行のコメントを使用すると難しいです。/* ... */

この問題を解決するより良い方法はありますか?

ベストアンサー1

このシェルスクリプトがあなたに適していることを確認してください。

#!/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"

おすすめ記事