sort -n bash空间分隔项数组的内容

时间:2016-04-26 11:11:50

标签: arrays bash sorting

我有这个结构::

.
├── b withe spaces.py
├── c.py
├── lib.py
├── show.sh
└── sub
    └── a.py

我想要这个结果::

$ bash ./show.sh
    9 lines c.py              => info from outside script
   17 lines a.py              => info from outside script
  300 lines b withe spaces.py => info from outside script
 1589 lines lib.py            => info from outside script
 1915 lines total             => info from outside script

wc -l ::

排序很容易
$ wc -l *.py */*.py | sort -n
    9 c.py
   17 sub/a.py
  300 b withe spaces.py
 1589 lib.py
 1915 total

所以我的出发点是::

array=(
$(find ./ -name "*.py" -print0 | while read -d $'\0' file
  do
    llines=$(cat $file | wc -l)
    analyse='ouput analyse from some script'
    printf "%s =\t%25s => %s" $llines $file $analyse
  done
  ))

for item in ${array[@]}; do echo $item; done| sort -n

2 个答案:

答案 0 :(得分:1)

根本不需要数组:

find ./ -name "*.py" -print0 | while read -d $'\0' file ; do
    llines=$(wc -l < "$file")
    analyse='ouput analyse from some script'
    # ----- you missed quoting these ---->vvv
    printf "%s =\t%s => %s\n" "$llines" "$file" "$analyse"
done | sort -k1nr

答案 1 :(得分:0)

你可以做得更轻松:

find . -name "*sh" -print0 | wc  --files0-from=- -l | sort -n | sed 's/\(^[0-9]\+\) \(.*\)/\1 lines \2 => info from outside script/'

在这种情况下,您不会单独为每个文件执行wc,这将节省一些时间。 另外wc将为您计算总数。