title: Bash script to Rename multiple files in subfolder to their folder name
body: <p>I have the following file structure:</p>
  
  <pre><code>Applications/Snowflake/applications/Salford_100/wrongname_120.nui; wrongname_200_d.nui
  Applications/Snowflake/applications/Salford_900/wrongname_120.nui; wrongname_200_d.nui
  Applications/Snowflake/applications/Salford_122/wrongname_120.nui; wrongname_200_d.nui
  </code></pre>
  
  <p>And I want to rename the fles to the same name as the directories they're in, but the files with "_d" at the end should retain its last 2 characters. The file pattern would always be "salford_xxx" where xxx is always 3 digits. So the resulting files would be:</p>
  
  <pre><code>Applications/Snowflake/applications/Salford_100/Salford_100.nui; Salford_100_d.nui
  Applications/Snowflake/applications/Salford_900/Salford_900.nui; Salford_900_d.nui
  Applications/Snowflake/applications/Salford_122/Salford_122.nui; Salford_122_d.nui
  </code></pre>
  
  <p>The script would run from a different location in </p>
  
  <pre><code>Applications/Snowflake/Table-updater
  </code></pre>
  
  <p>I imagine this would require a for loop and a sed regex, but Im open to any suggestions.
  (Thanks @ghoti for your advice)
  I've Tried this, which currently does not account for files with "_d" yet and I just get one file renamed correctly. Some help would be appreciated.</p>
  
  <pre><code>cd /Applications/snowflake/table-updater/Testing/applications/salford_*
  
  dcomp="$(basename "$(pwd)")"
  for file in *; do
  ext="${file##*.}"
  mv -v "$file" "$dcomp.$ext"
  
  done
  </code></pre>
  
  <p>Ive now updated the script following @varun advice (thank you) and it now also searches through all files in the parent dir that contain salford in the name, missing out the parent name. Please see below</p>
  
  <pre><code>#!/bin/sh
  #
  #  RenameToDirName2.sh
  #
  set -e
  
  cd /Applications/snowflake/table-updater/Testing/Applications/
  
  find salford* -maxdepth 1 -type d \( ! -name . \) -exec sh -c '(cd {}  &amp;&amp;
      (
          dcomp="$(basename "$(pwd)")"
          for file in *;
          do ext="${file#*.}"
              zz=$(echo $file|grep _d)
          if [ -z $zz ]
          then
              mv -v "$file" "$dcomp.$ext"
          else
              mv -v "$file" "${dcomp}_d.$ext"
      fi
  done
  )
  )' ';'
  </code></pre>
  
  <p>The thing is, I've just realised that in these salford sub directories there are other files with different extensions that I don't want renaming. Ive tried putting in an else if statement to stipulate *.Nui files only, calling my $dcomp variable, like this</p>
  
  <pre><code>    else
      if file in $dcomp/*.nui
      then
       #continue...
  </code></pre>
  
  <p>But I get errors. Where should this go in my script and also do I have the correct syntax for this loop? Can you help?</p>