Home > Back-end >  Is there a way to lowercase all subdirectory names using bash script?
Is there a way to lowercase all subdirectory names using bash script?

Time:01-17

I'm trying to format old files to fit/incorporate in our current automation of dataset processing. However, the directory and sub-directory names of the old files where all in upper case.

I don't exactly know how to do this using bash script. Is there a way to change all directory and sub-directory names to lower case?

CodePudding user response:

If you want to change the directories and subdirectories only (i.e. leave the files alone), you should go with the find command.

If you are using bash v. 4 or greater you can do it without invoking any other program but bash itself:

$ find . -mindepth 1 -depth -type d -execdir bash -c 'mv "${0}" "${0,,}"' "{}" \;

Otherwise, you need to convert the directory name by other means, e.g. tr:

$ find . -mindepth 1 -depth -type d -execdir bash -c \
  "ln=\$(echo \$0 | tr '[:upper:]' '[:lower:]') && mv \$0 \$ln" "{}" \;

Note that you must use -depth in order to change the directory names in depth-first order,

Also, you need -execdir instead of -exec to rename just one path element at a time.

CodePudding user response:

This may come handy:

$ var=AAA
$ echo ${var,}
aAA
$ echo ${var,,}
aaa

And to upper:

$ var=aaa
$ echo ${var^}
Aaa
$ echo ${var^^}
AAA

CodePudding user response:

tr may be of help, as in

echo HELLO | tr '[:upper:]' '[:lower:]'

So you may do something similar to

for i in $(ls)
do
  mv $i $(echo $i | tr '[:upper:]' '[:lower:]')
done

CodePudding user response:

With bash and Perl's standalone rename command with its sed syntax:

shopt -s globstar
rename -n 'y/[A-Z]/[a-z]/' **

If output looks okay, remove -n.

From: man bash:

globstar: If set, the pattern ** used in a pathname expansion context will match all files and zero or more directories and subdirectories. If the pattern is followed by a /, only directories and subdirectories match.

CodePudding user response:

A pure Bash find based concept

Based on enter image description here

Variations of the same command for higher flexibility:

  • find .: the period is going to search in the local directory you are in. If you'd like to analyse another folder, just replace the dot with the path to that folder. Example: $ find /path/to/another

  • -maxdepth 1: This is the depth the find command should take into consideration. 1 means, apply only on the subfolders of this folder (recursion level 1). -maxdepth 2 means, go into every subfolder and do the same (recursion level 2). ...

  • Related