Bash:查找最大行数的文件

Mar*_*era 7 unix bash awk sed wc

这是我尝试做到的

  • 查找所有*.java文件
    find . -name '*.java'
  • 数行
    wc -l
  • 删除最后一行
    sed '$d'
  • 使用AWK查找wc输出中的最大行数
    awk 'max=="" || data=="" || $1 > max {max=$1 ; data=$2} END{ print max " " data}'

然后将其合并为单行

find . -name '*.java' | xargs wc -l | sed '$d' | awk 'max=="" || data=="" || $1 > max {max=$1 ; data=$2} END{ print max " " data}'
Run Code Online (Sandbox Code Playgroud)

我可以以某种方式实现只计算非空行?

Sha*_*hin 16

find . -type f -name "*.java" -exec grep -H -c '[^[:space:]]' {} \; | \
    sort -nr -t":" -k2 | awk -F: '{print $1; exit;}'
Run Code Online (Sandbox Code Playgroud)

如果您还想查看非空行数,请替换该awk命令head -n1.


命令细分:

find . -type f -name "*.java" -exec grep -H -c '[^[:space:]]' {} \; 
'---------------------------'       '-----------------------'
             |                                   |
   for each *.java file             Use grep to count non-empty lines
                                   -H includes filenames in the output
                                 (output = ./full/path/to/file.java:count)

| sort -nr -t":" -k2  | awk -F: '{print $1; exit;}'
  '----------------'    '-------------------------'
          |                            |
  Sort the output in         Print filename of the first entry (largest count)
reverse order using the         then exit immediately
  second column (count)
Run Code Online (Sandbox Code Playgroud)


Vij*_*jay 8

find . -name "*.java" -type f | xargs wc -l | sort -rn | grep -v ' total$' | head -1
Run Code Online (Sandbox Code Playgroud)