具有文件保存和顺序文件命名的Linux shell脚本

时间:2014-12-03 15:20:49

标签: linux shell embedded-linux busybox dash-shell

我正在使用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

我需要按顺序命名文件。这是我发现的here代码,它对已存在的文件进行顺序重命名,但我注意到在重命名多个文件后再次执行代码时,交叉重命名会导致文件删除(我跑了当0001.jpg到0005.jpg中的文件存在于目录中时,代码文件0004.jpg被删除,因为查找cmd在文件0004之前列出了文件0005,因此它将两者交叉重命名,文件0004被删除。)< / p>

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

我正在寻找的是一个单一的shell脚本,可以被SBC每天多次请求,以便相机根据最后使用的数字拍摄照片,保存并按顺序命名(如果最新的文件是0005.jpg,下一张图片将被命名为0006.jpg) 在我附加的fisrt代码行中添加这个命名功能会很棒,这样我就可以将它包含在可由SBC调用的sh脚本中。

2 个答案:

答案 0 :(得分:1)

这是我实际测试并且似乎正在运行的代码,基于@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.

答案 1 :(得分:0)

当且仅当您的文件名除了数字部分之外都相同时,这将起作用,并且数字部分被填充到足以使它们具有相同的数字位数。

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"