Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux rename files based on another file in the directory?

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

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.

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

like image 398
Rob Williams Avatar asked Dec 16 '10 08:12

Rob Williams


People also ask

How do I rename a file in a different directory in Linux?

Rename Files with the mv Command If you specify a directory as the destination when using the mv command, the source file moves to that directory. If the destination is another file name, the mv command renames the source file to that name instead.

How do I automatically rename multiple files?

To batch rename files, just select all the files you want to rename, press F2 (alternatively, right-click and select rename), then enter the name you want on the first file. Press Enter to change the names for all other selected files.

Can you rename a file with CP?

By Using cp Command Here along with the file's path, the filename is also changed—the syntax for the cp command.


1 Answers

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
like image 63
SiegeX Avatar answered Sep 30 '22 19:09

SiegeX