如何在bash脚本中反转for循环 [英] How to reverse a for loop in a bash script

查看:90
本文介绍了如何在bash脚本中反转for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在bash脚本中反转for循环.有一个目录,其中包含以%Y%m.mp4命名的视频(201701.mp4; 201702.mp4,201703.mp4,...).循环应该以最早的文件名(例如201712.mp4)开始.如何反转我的for循环?

I need to reverse a for loop in a bash script. There is a directory with videos named after %Y%m.mp4 (201701.mp4; 201702.mp4, 201703.mp4, ...). The loop should start with the oldest filename (e.g. 201712.mp4) How to reverse my for loop?

outputdir="/path/to/video/monthly/"

for file in "$outputdir"*.mp4
do

echo $file

done

推荐答案

您可以通过以下方式以保留顺序列出文件:

You can list your files in a reserved order in the following way:

ls -1 $outputdir/*.mp4 | sort -r

因此,您可以在脚本中执行以下操作:

So in you script you can do:

outputdir="/path/to/video/monthly/"
for file in $(ls -1 $outputdir*.mp4 | sort -r)
do
   echo $file
done

注意:正如@Pesa指出的那样,该解决方案将无法使用带空格的文件名.如果您是这种情况,则应引用以下命令:"$(ls -1 $outputdir*.mp4 | sort -r)"并使用"$file"

NOTE: As @PesaThe pointed out this solution would fail to work with filenames with spaces. If it is the case for you, you should quote the command: "$(ls -1 $outputdir*.mp4 | sort -r)" and use "$file"

更新: 参见以下测试

mkdir test && cd $_
for i in {1..5}; do touch test_$i.txt; done
cd -

然后ls -1 test/*.txt将输出:

test/test_1.txt
test/test_2.txt
test/test_3.txt
test/test_4.txt
test/test_5.txt

然后ls -1 test/*txt | sort -r将输出:

test/test_5.txt
test/test_4.txt
test/test_3.txt
test/test_2.txt
test/test_1.txt

这篇关于如何在bash脚本中反转for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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