Programing

bash에서 (공백이 아닌) 코드 줄 수

lottogame 2020. 6. 21. 19:39
반응형

bash에서 (공백이 아닌) 코드 줄 수


Bash에서 프로젝트에서 공백이 아닌 코드 줄 수를 어떻게 계산합니까?


cat foo.c | sed '/^\s*$/d' | wc -l

그리고 주석을 빈 줄로 생각하면 :

cat foo.pl | sed '/^\s*#/d;/^\s*$/d' | wc -l

그러나 언어에 따라 다릅니다.


#!/bin/bash
find . -path './pma' -prune -o -path './blog' -prune -o -path './punbb' -prune -o -path './js/3rdparty' -prune -o -print | egrep '\.php|\.as|\.sql|\.css|\.js' | grep -v '\.svn' | xargs cat | sed '/^\s*$/d' | wc -l

위의 내용은 프로젝트 (현재 폴더 및 모든 하위 폴더를 재귀 적으로)에 대한 총 코드 줄 수 (공백 줄 제거)를 제공합니다.

위의 "./blog" "./punbb" "./js/3rdparty"및 "./pma"는 코드를 작성하지 않았기 때문에 차단 된 폴더입니다. 또한 .php, .as, .sql, .css, .js는보고있는 파일의 확장자입니다. 확장자가 다른 파일은 무시됩니다.


쉘 스크립트가 아닌 다른 것을 사용하려면 CLOC를 시도 하십시오 .

cloc는 많은 프로그래밍 언어에서 빈 줄, 주석 줄 및 소스 코드의 실제 줄을 계산합니다. 그것은 Perl v5.6 이상의 표준 배포판 (외부 모듈의 코드가 cloc에 내장되어 있음) 외부에 의존하지 않고 완전히 Perl로 작성되었으므로 이식성이 뛰어납니다.


공통 쉘 유틸리티를 사용하여이를 수행하는 많은 방법이 있습니다.

내 해결책은 다음과 같습니다.

grep -cve '^\s*$' <file>

이것은 <file>에서 행과 일치하지 않는 (-v) 행을 검색합니다. '^ \ s * $'는 행의 시작이며 그 뒤에 0 개 이상의 공백 문자가옵니다. 줄 끝까지 (즉, 공백 이외의 내용 없음) 일치하는 줄 대신 일치하는 줄 수 (-c)를 표시합니다.

로 파이핑하는 방법에 비해이 방법의 장점은 wc여러 파일을 지정하고 각 파일에 대해 별도의 수를 얻을 수 있다는 것입니다.

$ grep -cve '^\s*$' *.hh

config.hh:36
exceptions.hh:48
layer.hh:52
main.hh:39

'wc'는 줄, 단어, 문자를 계산하므로 모든 줄 (빈 줄 포함)을 계산하려면 다음을 사용하십시오.

wc *.py

빈 줄을 걸러 내려면 grep을 사용할 수 있습니다.

grep -v '^\s*$' *.py | wc

'-v'는 '^'와 일치하는 행을 제외한 모든 행을 출력하도록 grep에 지시합니다. '\ s *'는 0 이상의 공백 문자입니다. '$'는 행의 끝입니다. * .py는 계산하려는 모든 파일 (현재 dir의 모든 python 파일) 파이프 출력을 wc로 보냅니다. 나가.

나는 내 자신의 (정품) 질문에 대답하고 있습니다. 이것을 다루는 stackoverflow 항목을 찾을 수 없습니다.


이 명령은 비 공백 행 수를 계산합니다.
cat fileName | grep -v ^$ | wc -l
grep -v ^ $ 정규식 함수는 빈 줄을 무시합니다.


cat 'filename' | grep '[^ ]' | wc -l

트릭을 잘해야합니다.


grep -cvE '(^\s*[/*])|(^\s*$)' foo

-c = count
-v = exclude
-E = extended regex
'(comment lines) OR (empty lines)'
where
^    = beginning of the line
\s   = whitespace
*    = any number of previous characters or none
[/*] = either / or *
|    = OR
$    = end of the line

나는이 옵션을 게시했기 때문에 다른 옵션이 나에게 잘못된 답변을 주었다. 이것은 주석 줄이 / 또는 *로 시작하는 Java 소스에서 작동했습니다 (여러 줄 주석의 모든 줄에서 *를 사용합니다).


awk '/^[[:space:]]*$/ {++x} END {print x}' "$testfile"

다음은 프로젝트의 코드 줄을 세는 Bash 스크립트입니다. 소스 트리를 재귀 적으로 탐색하며 "//"를 사용하는 빈 줄과 한 줄 주석은 제외합니다.

# $excluded is a regex for paths to exclude from line counting
excluded="spec\|node_modules\|README\|lib\|docs\|csv\|XLS\|json\|png"

countLines(){
  # $total is the total lines of code counted
  total=0
  # -mindepth exclues the current directory (".")
  for file in `find . -mindepth 1 -name "*.*" |grep -v "$excluded"`; do
    # First sed: only count lines of code that are not commented with //
    # Second sed: don't count blank lines
    # $numLines is the lines of code
    numLines=`cat $file | sed '/\/\//d' | sed '/^\s*$/d' | wc -l`

    # To exclude only blank lines and count comment lines, uncomment this:
    #numLines=`cat $file | sed '/^\s*$/d' | wc -l`

    total=$(($total + $numLines))
    echo "  " $numLines $file
  done
  echo "  " $total in total
}

echo Source code files:
countLines
echo Unit tests:
cd spec
countLines

내 프로젝트 의 출력 결과는 다음과 같습니다 .

Source code files:
   2 ./buildDocs.sh
   24 ./countLines.sh
   15 ./css/dashboard.css
   53 ./data/un_population/provenance/preprocess.js
   19 ./index.html
   5 ./server/server.js
   2 ./server/startServer.sh
   24 ./SpecRunner.html
   34 ./src/computeLayout.js
   60 ./src/configDiff.js
   18 ./src/dashboardMirror.js
   37 ./src/dashboardScaffold.js
   14 ./src/data.js
   68 ./src/dummyVis.js
   27 ./src/layout.js
   28 ./src/links.js
   5 ./src/main.js
   52 ./src/processActions.js
   86 ./src/timeline.js
   73 ./src/udc.js
   18 ./src/wire.js
   664 in total
Unit tests:
   230 ./ComputeLayoutSpec.js
   134 ./ConfigDiffSpec.js
   134 ./ProcessActionsSpec.js
   84 ./UDCSpec.js
   149 ./WireSpec.js
   731 in total

즐겨! - 커란


그것은 프로젝트에있는 파일 수에 달려 있습니다. 이론적으로 당신은 사용할 수 있습니다

grep -c '.' <list of files>

find 유틸리티를 사용하여 파일 목록을 채울 수있는 위치.

grep -c '.' `find -type f`

파일 당 줄 수를 줄 것입니다.


현재 디렉토리에서 특정 파일 확장자를 가진 모든 비 공백 행을 재귀 적으로 계산하는 스크립트 :

#!/usr/bin/env bash
(
echo 0;
for ext in "$@"; do
    for i in $(find . -name "*$ext"); do
        sed '/^\s*$/d' $i | wc -l ## skip blank lines
        #cat $i | wc -l; ## count all lines
        echo +;
    done
done
echo p q;
) | dc;

샘플 사용법 :

./countlines.sh .py .java .html

If you want the sum of all non-blank lines for all files of a given file extension throughout a project:

while read line
do grep -cve '^\s*$' "$line"
done <  <(find $1 -name "*.$2" -print) | awk '{s+=$1} END {print s}'

First arg is the project's base directory, second is the file extension. Sample usage:

./scriptname ~/Dropbox/project/src java

It's little more than a collection of previous solutions.


grep -v '^\W*$' `find -type f` | grep -c '.' > /path/to/lineCountFile.txt

gives an aggregate count for all files in the current directory and its subdirectories.

HTH!


This gives the count of number of lines without counting the blank lines:

grep -v ^$ filename wc -l | sed -e 's/ //g' 

rgrep . | wc -l

gives the count of non blank lines in the current working directory.


There's already a program for this on linux called 'wc'.

Just

wc -l *.c 

and it gives you the total lines and the lines for each file.

참고URL : https://stackoverflow.com/questions/114814/count-non-blank-lines-of-code-in-bash

반응형