在shell中通过扩展来计算总文件大小

我们有一组包含lucene索引的目录。 每个索引是不同文件types的混合(通过扩展区分),例如:

0/index/_2z6.frq 0/index/_2z6.fnm .. 1/index/_1sq.frq 1/index/_1sq.fnm .. 

(大约有10个不同的扩展名)

我们希望通过文件扩展名获得总数,例如:

 .frq 21234 .fnm 34757 .. 

我已经尝试过du / awk / xargs的各种组合,但是发现这样做很棘手。

对于任何给定的扩展你使用

 find /path -name '*.frq' -exec ls -l {} \; | awk '{ Total += $5} END { print Total }' 

获取该types的文件总大小。

经过一番思考

 #!/bin/bash ftypes=$(find . -type f | grep -E ".*\.[a-zA-Z0-9]*$" | sed -e 's/.*\(\.[a-zA-Z0-9]*\)$/\1/' | sort | uniq) for ft in $ftypes do echo -n "$ft " find . -name "*${ft}" -exec ls -l {} \; | awk '{total += $5} END {print total}' done 

它将输出每个find的文件types的字节大小。

用bash version4,你只需要调用findlsawk没有必要了:

 declare -A ary while IFS=$'\t' read name size; do ext=${name##*.} ((ary[$ext] += size)) done < <(find . -type f -printf "%f\t%s\n") for key in "${!ary[@]}"; do printf "%s\t%s\n" "$key" "${ary[$key]}" done 

每隔一列由二分开. 和最后一部分(扩展名)保存在数组中。

 #!/bin/bash find . -type f -printf "%s\t%f\n" | awk ' { split($2, ext, ".") e = ext[length(ext)] size[e] += $1 } END{ for(i in size) print size[i], i }' | sort -n 

那么你得到每个扩展总大小以字节为单位。

 60055 gemspec 321991 txt 2075312 html 2745143 rb 13387264 gem 47196526 jar 

在Iain的脚本上扩展更快的版本,以处理大量的文件。

 #!/bin/bash ftypes=$(find . -type f | grep -E ".*\.[a-zA-Z0-9]*$" | sed -e 's/.*\(\.[a-zA-Z0-9]*\)$/\1/' | sort | uniq) for ft in $ftypes do echo -ne "$ft\t" find . -name "*${ft}" -exec du -bcsh '{}' + | tail -1 | sed 's/\stotal//' done 

这是解决scheme:

 find . -type f | grep -E ".*\.[a-zA-Z0-9]*$" | sed -e 's/.*\(\.[a-zA-Z0-9]*\)$/\1/' | sort | uniq -c | sort -n 

本帖最近公布的解决scheme: 获取目录中的所有扩展名及其各自的文件数

我解决了使用这两个命令:

 FILES=$(find . -name '*.c') stat -c %s ${FILES[@]} | awk '{ sum += $1 } END { print ".c" " " sum }' 

我对这个问题的回答是:

 #!/bin/bash date > get_size.log # Lists all files find . -type f -printf "%s\t%f\n" | grep -E ".*\.[a-zA-Z0-9]*$" | sort -h | awk ' { split($2, ext, ".") e = ext[length(ext)] # Checks that one extension could be found if(length(e) < length($2)) { # Check that file size are bigger than 0 if($i > 0) { # Check that extension not are integer if(!(e ~/^[0-9]+$/)) { size[e] += $1 } } } if(length(e) == length($2)) { size["blandat"] += $1 } } END{ for(i in size) print size[i], i }' | sort -n >> get_size.log echo echo echo The result are in file get_size.log 

试用螃蟹( http://etia.co.uk/ ) – 这是一个命令行工具,允许您使用SQL查询文件系统。