English 中文(简体)
名册上人数最多的档案名称,名字从数字开始
原标题:Find highest numbered filename in a directory where names start with digits
  • 时间:2009-10-19 05:09:04
  •  标签:

我有一份档案目录,这些档案类似:

001_something.php  002_something_else.php
004_xyz.php        005_do_good_to_others.php

我最终想建立一个新的、空洞的PHP档案,其名称始于该系列的下一个数字。

LIST=`exec ls $MY_DIR | sed  s/([0-9]+).*/1/g  | tr  
     `

前面的法典给我这样说:

LIST= 001 002 004 005  

我要 gr笑这005,一把.,然后用这一数字生成新的档案名称。 我如何在讲卫生运动中这样做?

最佳回答
$ LIST=($LIST)
$ newfile=`printf %03d-whatever $((10#${LIST[${#LIST}]}+1))`
$ echo $newfile
006-whatever

因此,这符合具体情况。 下面是任何-posix-shell- including-bash解决办法,我想象可能有一个更简单的办法。

$ cat /tmp/z
f () {
    eval echo ${$#} | sed -e  s/^0*// 
}
LIST= 001 002 004 005  
newname=`printf %03d-whatever $(($(f $LIST) + 1))`
echo $newname
$ sh /tmp/z
006-whatever
$ 
问题回答

你们是否需要整个LIST?

不适用

LAST=`exec ls $MY_DIR | sed  s/([0-9]+).*/1/g  | sort -n | tail -1`

只给你005部分,

printf "%03d" `expr 1 + $LAST`

将按顺序打印下一个数字。

仅使用标准工具,以下文件将预留新档案(006):

ls [0-9]* | sed  s/_/ _/  | sort -rn | awk  {printf "%03d", $1 + 1; exit} 

这似乎更为简单。

ls [0-9]* | sort -rn | awk  {FS="_"; printf "%03d_new_file.php
",$1+1;exit} 

快速、无舱位和无舱位(也处理有空位的档案名称)*:

list=([0-9]*)
last=${list[@]: -1}
nextnum=00$((10#${last%%[^0-9]*} + 1))
nextnum=${nextnum: -3}
touch ${nextnum}_a_new_file.php

鉴于你的例子,产出如下:

006_a_new_file.php
$ for file in *php; do last=${file%%_*} ; done
$ newfilename="test.php"
$ printf "%03d_%s" $((last+1)) $newfilename
006_test.php

i 允许你制作新的档案

  1. touch "newfile_$(printf "%03d" $(echo $(ls 00?_*.php|sed  s/_.*// |sort -rn|head -1)+1|bc))"
    

    2. 结 论

    num=$(ls 00?*.php|sed  s/.*// |sort -rn|head -1) 
    touch $(printf "newfile_%03d" $((num+1)))
    
    

我把这一答案放在对核心问题提出最低限度的解决办法上,即“在名字从数字开始的名录中填入最高档案名称”:

ls -1 "$MyDir" | sort -hr | head -n 1

The first statement puts out the files in MyDir as one liners with the -1 option. This is piped to the sort function which sorts in human numeric order with -h and in reverse order (highest number first) with -r. This is piped to the head function which just delivers the -n top most results (1 in the example). The answer considers human numeric sort order i.e. 221 is higher than 67. It is a POSIX shell solution so highly compatible.

这里的解决办法(青年需要bc):

#!/bin/bash

LIST= 001 002 008 005 004 002  
a=0

for f in $LIST
do
    t=$(echo $f + 1|bc)
    if [ $t -ge $a ]
    then
        a=$t
    fi
done

printf "%03d
" $a




相关问题
热门标签