1

I need a little help finishing a script to rename a folders files sequentially to the folder name. I would have thought this would be a common action, but I can't seem to find exactly what Im looking for after searching. I found something that works to rename the files sequentially, but I want to append the folder or directory name to the front of the file.

#!/bin/bash
a=1
for i in *.jpg; do
  new=$(printf "%04d.jpg" ${a}) #04 pad to length of 4
  mv ${i} ${new}
  let a=a+1
done

So I want these folders and files:

~/tmp/6856u56u56.jpg
~/tmp/7567787.jpg

~/tmp2/46u65h5hh.jpg
~/tmp2/b656hy6hjh.jpg

to look like:

~/tmp/UG-tmp-001.jpg
~/tmp/UG-tmp-002.jpg

~/tmp2/UG-tmp2-001.jpg
~/tmp2/UG-tmp2-002.jpg

~/tmp/(text)-(directory name)-(sequential numbering).(extension)

after running the script.

Could anyone help me out? Also, the file's aren't necessarily .jpg, and the folder might have spaces in the name. If this is a problem please let me know. This is for linux using a bash script. If it works well I'll probably try to get it integrated into the right click of the file manager. Thanks in advance!

1 Answers1

0

Looking at the expected results, this code should work

#!/bin/bash
a=1
result=$(printf '%s\n' "${PWD##*/}")
echo $result
filename="text-$result-"  #replace text with what you need
for i in *.jpg; do
  newfilename="$filename$a.jpg" # since the extension is does not change you can hardcode it
  echo $newfilename
  mv ${i} ${newfilename}
  let a=a+1
done
gpr
  • 485
  • 1
  • 5
  • 15
  • I missed the extensions can change part in your question, you can easily get the extensions of the file in a variable and append it refer http://stackoverflow.com/questions/965053/extract-filename-and-extension-in-bash – gpr Oct 22 '13 at 05:09
  • Thanks! I'm getting an error though that was messing me up when I tried figuring it out myself, it must be distro specific or something. I'm on opensuse and I'm getting an "mv: target ‘blah-12.jpg’ is not a directory" error message. Do you know how to fix this by any chance? Thanks for your help! – user2905513 Oct 24 '13 at 01:35
  • Update: I figured it out after a search, I added "IFS=''" before the script and it fixed the spaces in filename problem. I would really like to have it show zeros when numbering though, like 0001 instead of just 1. I'll try to figure it out myself, but if you know how to fix that and dont mind, I would appreciate it! Thanks! – user2905513 Oct 24 '13 at 01:40
  • you can use this `printf -v j "%05d" $a` and assign the variable `newfilename` as `newfilename=$filename$j` . The printf statment formats the value of `a` by prepending zeros such that the number of digits are always 5. The value is stored in variable `j`. – gpr Oct 24 '13 at 04:40
  • A small script as a demo `#!/bin/bash a=1 while [ $a -lt 300 ] do let a=a+1 printf -v j "%05d" $a echo $j; done; ` – gpr Oct 24 '13 at 04:42