什么正确地遍历这个 [英] whats the correct way to loop this

查看:191
本文介绍了什么正确地遍历这个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在哪里inotifywait被管道输送到一个while循环执行以下逻辑的脚本。

I have a script where inotifywait is piped into a while loop that executes the following logic.

     cp "$S3"/2/post2.png "$S3";
     mv "$S3"/1/post1.png "$S3"/2/post2.png;
     cp "$S3"/3/post3.png "$S3";
     mv "S3"/post2.png "$S3"/3/post3.png;

等等等等.....然后在脚本的末尾...

so forth and so on..... then at the end of the script...

     mv "$dir"/$file "$S3"/1/post1.png

这行再presents一个新的帖子,上面是旧的岗位轮换。

That line represents a fresh post, the above is the rotation of older post.

我可以用手code迭代一路下跌到100多个,但我想更有效地计划,节省时间。

I can can hand code the iterations all the way down to 100+, but I would like to program more efficiently and save time.

那么,什么是正确的一些方法来循环呢?

So, what's some correct ways to loop this?

推荐答案

我想一个更好的机制将列出在$ S3目录反向数字顺序,并安排处理它们这样。如果100个目录都present,或者是否需要创建目前尚不清楚。我们假设目录1..100可能存在,以及目录的 N 的永远,只包含的 postN.png

I think a better mechanism would list the directories in "$S3" in reverse numeric order, and arrange to process them like that. It isn't clear if the 100 directories are all present or whether they need to be created. We'll assume that directories 1..100 might exist, and directory N will always and only contain postN.png.

我假设没有空格,换行或其他尴尬字符文件路径;这意味着 LS 可没有太多的风险中。

I'm assuming that there are no spaces, newlines or other awkward characters in the file paths; this means that ls can be used without too much risk.

for dirnum in $(cd "$S3"; ls */*.png | sed 's%/.*%%' | sort -nr)
do
    next=$(($dirnum + 1))
    mv "$S3/$dirnum/post$dirnum.png" "$S3/$next/post$next.png"
done

CD$ S3意味着我没有得到包括在输出一个可能长路径名; 。在 LS * / * PNG 列出了存在的文件; sed的删除文件名和斜线,只留下一个包含文件的目录编号列表;和排序会将目录反向数字顺序。

The cd "$S3" means I don't get a possibly long pathname included in the output; the ls */*.png lists the files that exist; the sed removes the file name and slash, leaving just a list of directory numbers containing files; and the sort puts the directories in reverse numeric order.

的其余部分是直线前进,鉴于这样的假设必要的目录已经存在。它不会是很难添加 [-d$ S3 / $下一个] || MKDIR -p$ S3 / $下一个移动文件之前。显然,在循环后,您可以使用您的最后一个命令:

The rest is straight-forward, given the assumption that the necessary directories already exist. It would not be hard to add [ -d "$S3/$next" ] || mkdir -p "$S3/$next" before moving the file. Clearly, after the loop you can use your final command:

mv "$dir/$file" "$S3/1/post1.png"

请注意,我已经用双引号括完整名称;如果事情收购空格意外通常会导致更少的讨厌的惊喜。

Note that I've enclosed complete names in double quotes; it generally leads to fewer nasty surprises if something acquires spaces unexpectedly.

这篇关于什么正确地遍历这个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆