简体   繁体   English

当目录内容更改时,shell脚本增加文件名(centos)

[英]shell script to increment file names when a directory contents changes (centos)

I have a folder containing 100 pictures from a webcam. 我有一个文件夹,其中包含来自网络摄像头的100张照片。 When the webcam sends a new picture, I want this one to replace number 0 and have all the other jpg's move up one number. 当网络摄像头发送新图片时,我希望此图片替换数字0,并使所有其他jpg的图片向上移动一个数字。 I've set up a script where inotify monitors a directory. 我设置了一个脚本,其中inotify监视目录。 When a new file is put into this directory the script renumbers all the files in the picture directory, renames the new uploaded picture and puts it in the folder with the rest. 将新文件放入此目录时,脚本会对图片目录中的所有文件重新编号,重命名新上传的图片,并将其与其余图片一起放入文件夹中。 This script 'sort of' works. 这个脚本的“排序”的作品。 'Sort of', because sometimes it does what it's supposed to do and sometimes it complains about missing files: “排序”,因为有时会执行应做的事情,有时会抱怨缺少文件:

mv: cannot stat `webcam1.jpg': No such file or directory mv:无法统计`webcam1.jpg':没有这样的文件或目录

Sometimes it complains about only one file, sometimes 4 or 5. Of course I made sure all 100 files were there, properly named before the script was run. 有时它只抱怨一个文件,有时是4或5。当然,我确保所有100个文件都存在,并且在运行脚本之前已正确命名。 After the script is run, the files it complains about are indeed missing. 运行脚本后,它抱怨的文件确实丢失了。 This is the script, in the version I tested the full paths to the directories are used of course. 这是脚本,在我测试的版本中,当然使用了目录的完整路径。

#!/bin/bash
dir1= /foo # directory to be watched
while inotifywait -qqre modify "$dir1"; do
cd /f002 #directory where the images are
for i in {99..1}
do
 j=$(($i+1))
 f1a=".jpg"
 f1="webcam$i$f1a"
 f2="test"
 f2="webcam$j$f1a"
 mv $f1 $f2 
done
rm webcam100.jpg
mv dir1/*.jpg /f002/webcam0.jpg 
done

I also need to implement some error checking, but for now I don't understand why it is missing files that are there. 我还需要实现一些错误检查,但是现在我不明白为什么它会丢失那里的文件。

You are executing the following mv commands: 您正在执行以下mv命令:

mv webcam99.jpg webcam100.jpg
...
mv webcam1.jpg webcam2.jpg

The mv webcam0.jpg to webcam1.jpg is missing. mv webcam0.jpg到webcam1.jpg丢失。 With the first change to "$dir" you have the following files in /foo2: 首次更改为“ $ dir”时,/ foo2中具有以下文件:

webcam99.jp
...
webcam2.jpg
webcam0.jpg

With subsequent "$dir" change you will have the following: 通过随后的“ $ dir”更改,您将具有以下内容:

webcam99.jp
...
webcam3.jpg
webcam0.jpg

In other words -- you are forgetting to move webcam0.jpg to webcam1.jpg. 换句话说,您忘记将webcam0.jpg移至webcam1.jpg。 I would modify your script like this: 我会这样修改您的脚本:

rm webcam99.jpg
for i in {98..0}
do
     j=$(($i+1))
     f1a=".jpg"
     f1="webcam$i$f1a"
     f2="test"
     f2="webcam$j$f1a"
     mv $f1 $f2 
done
mv dir1/*.jpg /f002/webcam0.jpg 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM