基于文件名中的数字索引对目录中的文件进行排序

时间:2011-11-21 11:03:56

标签: linux bash shell sorting awk

我在我的脚本中使用了for循环......

 for var in ipsec_packet*.txt; do
 echo $var
 done

输出

ipsec_packet10.txt
ipsec_packet11.txt
ipsec_packet12.txt
ipsec_packet13.txt
ipsec_packet14.txt
ipsec_packet15.txt
ipsec_packet16.txt
ipsec_packet17.txt
ipsec_packet18.txt
ipsec_packet1.txt
ipsec_packet2.txt
ipsec_packet3.txt
ipsec_packet4.txt
ipsec_packet5.txt
ipsec_packet6.txt
ipsec_packet7.txt
ipsec_packet8.txt
ipsec_packet9.txt

但是我希望它们从1到最大的可用(这里是18)按照这样的排序顺序...

ipsec_packet1.txt
ipsec_packet2.txt
... 
...
ipsec_packet18.txt

我尝试了sort -n k14,但没有帮助。请告诉我一些变种或任何其他bash / awk功能可以帮助我。

4 个答案:

答案 0 :(得分:3)

您可以尝试使用sort -V选项,用于文本中数字的自然排序

for var in `ls ipsec_packet*.txt | sort -V`; do  echo $var; done

答案 1 :(得分:1)

如果 GNU sort 不可用(即不支持 -V )且 Perl 是可接受的:

perl -le'
  print join $/, 
    map $_->[1], 
      sort { 
        $a->[0] <=> $b->[0] 
        } map [/(\d+)\./, $_], 
          glob shift
  ' '*.txt'

可替换地:

printf '%s\n' *.txt |
  sed 's/.*[^0-9]\([0-9]*\)\./\1,&/' |
    sort -n |
      cut -d, -f2-

答案 2 :(得分:0)

我更希望codaddict's solution,但是当sed没有sort时,这是一个sort + -V技巧:

for var in $(ls ipsec_packet*.txt | sed 's/[0-9]/\t&/' | sort -n -k2 | sed 's/\t//')
do
    echo $var
done

您可以将\t替换为输入数据中未显示的任何单个字符,并将该字符指定为sort的{​​{1}}字段分隔符。

答案 3 :(得分:0)

这可能对您有用:

ls -v ipsec_packet*.txt