Renaming Pattern Based Directories in Bash

I have a Bash script that is well suited for simply renaming directories that match the criteria.

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

Currently, if the directory is as follows:

user1 [files.sentfrom.com] - Directory-Subject

It renames the directory and only the directory looks like

Directory-Subject (this could have different type of text)

How to change script / search criteria for search

www.ibm.com - Directory-Subject

and rename the directory and only the directory to

Directory-Subject
+4
source share
2 answers

You can write your code in such a way that it covers both cases:

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

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
0
source

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

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

, , glob

0

Source: https://habr.com/ru/post/1669509/


All Articles