简体   繁体   中英

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

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.

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"
#!/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.

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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