title: (Automator/AppleScript) Rename files to a folder name, save to different folder & add prefix
body: <p>I really need you help and will be very grateful for it.
  I think this should be no problem for you.</p>
  
  <p>So I have folder with different subfolders in it. In subfolders are images.
  What I need is:</p>
  
  <ol>
  <li>Change each image name to it’s subfolder name + 001 and so on («1stSubfolder001, 1stSubfolder002, …», «2ndSubfolder001, 2ndSubfolder002, …»)</li>
  <li>Move all images from all subfolders to one folder (or at least to root folder)</li>
  <li>Add random prefix number to names.</li>
  </ol>
  
  <p>I have script to third task:</p>
  
  <pre><code>tell application "Finder" 
      repeat with this_item in (get items of window 1)
          set name of this_item to ((random number from 0 to 99999) &amp; name of this_item) as string
      end repeat 
  end tell
  </code></pre>
  
  <p>But it only works with opened folder on the foreground. Maybe there is a way to make one script to run it on the background?</p>
  
  <p>Huge thank you in advance.</p>
  
  <p>I found cool automator app here, but I need to correct it a little bit.
  <a href="https://stackoverflow.com/questions/15831913/how-do-i-use-the-current-folder-name-without-a-path-as-a-variable-in-automator-i">How do I use the current folder name without a path as a variable in automator in Mac?</a></p>
  
  <p>This script does everything I need BUT it renames all files to ONE folder name, not each different.</p>
  
  <p>Here is another applescript that does rename files to folders, but it uses 2 folders name (folder + subfolder), and I need only subfolder prefix.</p>
  
  <pre><code>set myFolder to do shell script "sed 's/\\/$//' &lt;&lt;&lt; " &amp; quoted form of POSIX path of (choose folder)
  set myFiles to paragraphs of (do shell script "find " &amp; quoted form of myFolder &amp; " \\! -name \".*\" -type f -maxdepth 2 -mindepth 2")
  repeat with aFile in myFiles
      tell application "System Events" to set file aFile's name to (do shell script "sed 's/.*\\/\\([^/]*\\)\\/\\([^/]*\\)\\/\\([^/]*$\\)/\\1_\\2_\\3/' &lt;&lt;&lt; " &amp; quoted form of aFile)
  end repeat  
  </code></pre>
  
  <p>(MacBook Pro Late 2013, OS X Yosemite 10.10.1)</p>