为增量扩展的Unix shell脚本 [英] Unix shell script for increment the extension
问题描述
我有文件中获取生成(testfile的)eachtime脚本在工作目录中运行。我要生成的文件复制到一个目录(testfolder),并交由.EXT递增
I have file getting generated (testfile) eachtime a script is run in working directory. I have to copy that generated file to a directory (testfolder) and have it incremented by a .ext
如果脚本运行首次然后复制到testfile将作为testfoldertestfile.0,并在运行时第二次复制到testfile将作为testfoldertestfile.1等。
If the script is run for first time then copy the testfile to testfolder as "testfile.0" and when run second time copy the testfile to testfolder as "testfile.1" and so on.
我的脚本:
#!/bin/sh
file="testfile"
n=1
ls folder/${file}* | while read i
do
if [ folder/${file}.${n} = ${i} ]
then
n=$(( $n + 1 ))
fi
done
cp testfile folder/${file}.${n}
这是只工作了第一个增量的文件夹/ testfile.0
this is only working for first increment "folder/testfile.0"
推荐答案
我不纠正你的解决方案,因为mklement0是否良好。
I won't correct your solution, since mklement0 does it well.
下面是另一种解决方案,没有任何的循环:
Here is another solution, without any loop:
file="testfile"
n_max=$(ls -1 "folder/${file}"* | egrep -o '[0-9]+$' | sort -rn | head -n 1)
cp "${file}" "folder/${file}.$((n_max+1))"
这是第二行的事情:首先你列出文件,那么 egrep的
提取数字扩展,那么排序-rg
对其进行排序递减,而去年头
只抓的第一行,也就是最大的二手指数。最后,在第三行,你加一此上限来构建新的索引。这是我的脚本确定,如果该列表是空的。
Here is the thing of the second line: first you list the files, then egrep
extracts the digit extension, then sort -rg
sorts them decreasingly, and last head
catchs only the first line, i.e. the largest used index. Finally, in the third line, you add one to this max to build your new index. It is ok on my script if the list is empty.
顺便说一句,列出一个目录可能会很长,所以我建议你在一些地方保存您用于以后使用的最后一个索引。将其保存为一个变量在脚本,甚至在文件中...它可以节省你也一段时间了。
By the way, listing a directory may be quite long, so I suggest you to store somewhere the last index you used for later use. Save it as a variable in the script, or even in a file ... it can save you also some time.
这篇关于为增量扩展的Unix shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!