Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rename files with .jpg extension according to its folder name via bash script

Tags:

linux

bash

shell

I have .jpg file in my folder and its sub folders.

image/1/large/imagexyz.jpg 
image/1/medium/imageabc.jpg
image/1/small/imagedef.jpg

and so on for 2,3,4 ...

I need to rename all image files with its folder name. ie. imagexyz.jpg should be large_1.jpg and imageabc.jpg should be medium_1.jpg and so on.

like image 622
Prabesh Shrestha Avatar asked Mar 18 '11 10:03

Prabesh Shrestha


4 Answers

oldIFS="$IFS"
IFS=/
while read -r -d $'\0' pathname; do
  # expect pathname to look like "image/1/large/file.name.jpg"
  set -- $pathname
  mv "$pathname" "$(dirname "$pathname")/${3}_${2}.jpg"
done < <(find . -name \*.jpg -print0)
IFS="$oldIFS"
like image 135
glenn jackman Avatar answered Oct 16 '22 00:10

glenn jackman


#!/bin/sh
find . -type f -name "*.$1" > list
while read line
do
echo $line
first=`echo $line | awk -F/ '{print $2}'`
echo $first 
second=`echo $line | awk -F/ '{print $3}'`
echo $second
name=`echo $line | awk -F/ '{print $4}'`
echo $name

mv "./$first/$second/$name" ./$first/$second/${first}_${second}.$1

done < list

If you save this file as rename.sh then run rename.sh jpg to replace jpg files and rename.sh png to replace png and so on.

like image 34
Succeed Stha Avatar answered Oct 15 '22 22:10

Succeed Stha


Did you mean something like that?

for i in $(find image/ -type f); do 
  mv $i $(echo $i | sed -r 's#image/([0-9]+)/([^/]+)/[^/]+.jpg#\2_\1.jpg#'); 
done

This will move all files from image/$number/$size/$file.jpg to ./${size}_${number}.jpg.

But be aware that you will overwrite your files if there is more than one .jpg file in each image/$number/$size directory (see comment of kurumi).

like image 44
bmk Avatar answered Oct 15 '22 23:10

bmk


A solution based upon native bash functions (well, except find, then ;-) )

#!/bin/bash

files=`find . -type f -name *.jpg`
for f in $files
do
     echo
     echo $f
     # convert f to an array
     IFS='/'
     a=($f)
     unset IFS
     # now, the folder containing a digit
     # are @ index [2]
     # small, medium, large are @ [3]
     # and name of file @ [4]

     echo ${a[2]} ${a[3]} ${a[4]}
     echo ${a[3]}_${a[2]}.jpg
done
like image 28
Fredrik Pihl Avatar answered Oct 16 '22 00:10

Fredrik Pihl