Renaming directories based on a pattern in Bash Renaming directories based on a pattern in Bash shell shell

Renaming directories based on a pattern in Bash


You could write your code this way so that it covers both the cases:

for dir in *\ -\ *; do  [[ -d "$dir" ]] || continue   # skip if not a directory  sub="${dir#* - }"  if [[ ! -e "$sub" ]]; then    mv "$dir" "$sub"  fidone

Before running the script:

$ ls -1d */user1 [files.sentfrom.com] - Directory-Subject/www.ibm.com - Directory-Subject

After:

$ ls -1d */Directory-Subject/www.ibm.com - Directory-Subject/   # didn't move because directory existed already


A simple answer would be to change *\[*\]\ -\ * to *\ -\ *

for name in *\ -\ *; do  if [[ -d "$name" ]] && [[ ! -e "${name#* - }" ]]; then    mv "$name" "${name#* - }"  fidone

For more information, please read glob and wildcards