我需要在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循环
发布评论