简体   繁体   English

Bash脚本以相反的顺序复制编号的文件

[英]Bash script to copy numbered files in reverse order

I have a sequence of files: 我有一系列文件:

image001.jpg
image002.jpg
image003.jpg

Can you help me with a bash script that copies the images in reverse order so that the final result is: 您能帮我一个bash脚本,该脚本以相反的顺序复制图像,以便最终结果是:

image001.jpg
image002.jpg
image003.jpg
image004.jpg  <-- copy of image003.jpg
image005.jpg  <-- copy of image002.jpg
image006.jpg  <-- copy of image001.jpg

The text in parentheses is not part of the file name. 括号中的文本不是文件名的一部分。

Why do I need it? 我为什么需要它? I am creating video from a sequence of images and would like the video to play "forwards" and then "backwards" (looping the resulting video). 我正在根据一系列图像创建视频,并且希望视频先播放“前进”,然后播放“后退”(循环播放结果视频)。

You can use printf to print a number with leading 0s. 您可以使用printf打印以0开头的数字。

$ printf '%03d\n' 1
001
$ printf '%03d\n' 2
002
$ printf '%03d\n' 3
003

Throwing that into a for loop yields: 将其扔进for循环会产生:

MAX=6

for ((i=1; i<=MAX; i++)); do
    cp $(printf 'image%03d.jpg' $i) $(printf 'image%03d.jpg' $((MAX-i+1)))
done

I think that I'd use an array for this... that way, you don't have to hard code a value for $MAX. 我认为我将为此使用数组...这样,您不必为$ MAX硬编码一个值。

image=( image*.jpg )
MAX=${#image[*]}
for i in ${image[*]}
do
   num=${i:5:3} # grab the digits
   compliment=$(printf '%03d' $(echo $MAX-$num | bc))
   ln $i copy_of_image$compliment.jpg
done

I used 'bc' for arithmetic because bash interprets leading 0s as an indicator that the number is octal, and the parameter expansion in bash isn't powerful enough to strip them without jumping through hoops. 我使用“ bc”进行算术运算,因为bash将前导0解释为数字是八进制的指示符,并且bash中的参数扩展功能不足以剥离它们而不用跳过箍。 I could have done that in sed, but as long as I was calling something outside of bash, it made just as much sense to do the arithmetic directly. 我本可以在sed中完成此操作,但是只要我在bash之外调用某些东西,直接进行算术就很有意义。

I suppose that Kuegelman's script could have done something like this: 我认为Kuegelman的脚本可以完成以下操作:

MAX=(ls image*.jpg | wc -l)

That script has bigger problems though, because it's overwriting half of the images: 但是,该脚本有更大的问题,因为它会覆盖一半的图像:

cp image001.jpg image006.jpg # wait wait!!! what happened to image006.jpg???

Also, once you get above 007, you run into the octal problem. 同样,一旦达到007以上,就会遇到八进制问题。

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

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