bash - Unix shell script for increment the extension -
i have file getting generated (testfile) eachtime script run in working directory. have copy generated file directory (testfolder) , have incremented .ext
if script run first time copy testfile testfolder "testfile.0" , when run second time copy testfile testfolder "testfile.1" , on.
my script:
#!/bin/sh file="testfile" n=1 ls folder/${file}* | while read if [ folder/${file}.${n} = ${i} ] n=$(( $n + 1 )) fi done cp testfile folder/${file}.${n}
this working first increment "folder/testfile.0"
i won't correct solution, since mklement0 well.
here solution, without 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))"
here thing of second line: first list files, egrep
extracts digit extension, sort -rg
sorts them decreasingly, , last head
catchs first line, i.e. largest used index. finally, in third line, add 1 max build new index. ok on script if list empty.
by way, listing directory may quite long, suggest store somewhere last index used later use. save variable in script, or in file ... can save time.
Comments
Post a Comment