与文件的保存和顺序文件命名的Linux shell脚本(Linux shell script wit

2019-11-03 11:49发布

我用自带的Busybox的一个以太网相机工作。
单板计算机通过RS232连接到它。 在SBC需要发送一个命令到相机,以便采取一个jpg快照,保存到CF存储卡,并命名为按顺序(0001,0002等)。
这是我使用采取一个快照,没有顺序命名的代码:

wget http://127.0.0.1/snap.php -O /mnt/0/snapfull`date +%d%m%y%H%M%S`.jpg

我需要的文件被顺序命名。 这是我发现的代码在这里 ,做对已存在的文件顺序重命名,但我注意到,当代码被执行多个文件的重命名后,再一次,跨重命名可能会导致文件删除(我跑的代码时,文件从0001.JPG到0005.jpg存在于目录和文件0004.JPG被删除,因为查找CMD文件0004之前列出的文件0005,因此它跨改名都和文件0004被删除。)

find . -name '*.jpg' | awk 'BEGIN{ a=0 }{ printf "mv %s %04d.jpg\n", $0, a++ }' | dash

我所寻找的,是可以由SBC被要求每天多次一个shell脚本,让相机拍摄照片,保存它,并将它命名的顺序,根据所使用的最后一个数字(如果最新的文件是0005.jpg,下一张照片将被命名为0006.jpg)。
这将是巨大的,添加此命名功能的代码我附上最前一页线,这样我就可以将其包含在sh脚本可以由SBC调用。

Answer 1:

这将工作当且仅当你的文件名是除了数字部分都是相同的,而数字部分填充,以至于它们都是相同的位数。

set -- *.jpg           # put the sorted list of names on argv
while [ $# -gt 1 ]; do # as long as there's more than one...
  shift                # ...pop something off the beginning...
done
num=${1#*snapfull}                  # trim the leading alpha part of the name
num=${num%.*}                       # trim the trailing numeric part of the name
printf -v num '%04d' "$((num + 1))" # increment the number and pad it out

wget http://127.0.0.1/snap.php -O "snapfull${num}.jpg"


Answer 2:

这是我在实际测试代码,似乎基于@Charles答案是工作,:

#!/bin/sh
set -- *.jpg             # put the sorted list of picture namefiles on argv ( the number of files on the list can be requested by echo $# ) 
while [ $# -gt 1 ]; do   # as long as the number of files in the list is more than 1 ...
  shift                  # ...some rows are shifted until only one remains
done
if [ "$1" = "*.jpg" ]; then   # If cycle to determine if argv is empty because there is no jpg      file present in the dir.
  set -- snapfull0000.jpg     # argv is set so that following cmds can start the sequence from 1 on.
else
  echo "More than a jpg file found in the dir."
fi

num=${1#*snapfull}                     # 1# is the first row of $#. The alphabetical part of the filename is removed.
num=${num%.*}                          # Removes the suffix after the name.
num=$(printf "%04d" "$(($num + 1))")   # the variable is updated to the next digit and the number is padded (zeroes are added) 

wget http://127.0.0.1/snapfull.php -O "snapfull${num}.jpg" #the snapshot is requested to the camera, with the sequential naming of the jpeg file.


文章来源: Linux shell script with file saving and sequential file naming