Linux根据目录中的另一个文件重命名文件?

时间:2021-08-06 02:22:55

I've got about 750 directories that contain two files each:

我有大约750个目录,每个目录包含两个文件:

long_somewhat_random_filename.jpg
thumb.jpg

What I'd like to do is use find or something similar to rename thumb.jpg to long_somewhat_random_filename_thumb.jpg. My brain's kinda fuzzy at the moment.

我想做的是使用find或类似的东西将thumb.jpg重命名为long_somewhat_random_filename_thumb.jpg。此刻我的大脑有点模糊。

I could do it with a perl script, but if there's a somewhat easy way to do it in bash, that's easier.

我可以使用perl脚本来完成它,但如果在bash中有一个简单的方法,那就更容易了。

1 个解决方案

#1


9  

Give the script below a shot. Right now the echo makes it benign so you can try before you buy so to speak. If you like what you see, remove the echo and run the script again to actually make the changes.

将脚本放在下面。现在,回声使它变得温和,所以你可以在购买之前试试。如果您喜欢所看到的内容,请删除回显并再次运行脚本以实际进行更改。

#!/bin/bash

while read file; do
 echo mv "${file%/*}/thumb.jpg" "${file%.*}_thumb.jpg"
done < <(find . -type f ! -name "thumb.jpg" -name "*.jpg")

Input

$ find . -type f -name "*.jpg"
./dir1/dir1_foo_bar.jpg
./dir1/thumb.jpg
./dir2/dir2_foo_bar.jpg
./dir2/thumb.jpg
./dir3/dir3_foo_bar.jpg
./dir3/thumb.jpg
./dir4/dir4_foo_bar.jpg
./dir4/thumb.jpg
./dir5/dir5_foo_bar.jpg
./dir5/thumb.jpg

Output

$ ./mvthumb.sh
mv ./dir1/thumb.jpg ./dir1/dir1_foo_bar_thumb.jpg
mv ./dir2/thumb.jpg ./dir2/dir2_foo_bar_thumb.jpg
mv ./dir3/thumb.jpg ./dir3/dir3_foo_bar_thumb.jpg
mv ./dir4/thumb.jpg ./dir4/dir4_foo_bar_thumb.jpg
mv ./dir5/thumb.jpg ./dir5/dir5_foo_bar_thumb.jpg

#1


9  

Give the script below a shot. Right now the echo makes it benign so you can try before you buy so to speak. If you like what you see, remove the echo and run the script again to actually make the changes.

将脚本放在下面。现在,回声使它变得温和,所以你可以在购买之前试试。如果您喜欢所看到的内容,请删除回显并再次运行脚本以实际进行更改。

#!/bin/bash

while read file; do
 echo mv "${file%/*}/thumb.jpg" "${file%.*}_thumb.jpg"
done < <(find . -type f ! -name "thumb.jpg" -name "*.jpg")

Input

$ find . -type f -name "*.jpg"
./dir1/dir1_foo_bar.jpg
./dir1/thumb.jpg
./dir2/dir2_foo_bar.jpg
./dir2/thumb.jpg
./dir3/dir3_foo_bar.jpg
./dir3/thumb.jpg
./dir4/dir4_foo_bar.jpg
./dir4/thumb.jpg
./dir5/dir5_foo_bar.jpg
./dir5/thumb.jpg

Output

$ ./mvthumb.sh
mv ./dir1/thumb.jpg ./dir1/dir1_foo_bar_thumb.jpg
mv ./dir2/thumb.jpg ./dir2/dir2_foo_bar_thumb.jpg
mv ./dir3/thumb.jpg ./dir3/dir3_foo_bar_thumb.jpg
mv ./dir4/thumb.jpg ./dir4/dir4_foo_bar_thumb.jpg
mv ./dir5/thumb.jpg ./dir5/dir5_foo_bar_thumb.jpg