Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a subdirectory for all directories in folder

Suppose I have some directory, which contain a number of subdirectories, and in each of those subdirectories I want to create a directory with the same name:

./dir-1
./dir-2
...
./dir-n

I want to do mkdir */new-dir

but this throws an error. What's the best way of going about this?

like image 607
Scott Ritchie Avatar asked Jun 25 '13 06:06

Scott Ritchie


People also ask

How do I create a directory and subdirectories?

To create a directory in MS-DOS or the Windows Command Prompt (cmd), use the md or mkdir MS-DOS command. For example, below, we are creating a new directory called "hope" in the current directory. You can also create multiple new directories in the current one with the md command.

How do I make multiple folders and subfolders in one go?

Simply hold down the Shift key and click with the right mouse button in the Explorer on the folder where you want to create additional subfolders.

How do you create multiple sub directories in one command in Linux?

You can create directories one by one with mkdir, but this can be time-consuming. To avoid that, you can run a single mkdir command to create multiple directories at once. To do so, use the curly brackets {} with mkdir and state the directory names, separated by a comma.

Which command create a directory are subdirectory?

MS-DOS command is used to create a subdirectory is MKDIR. A subdirectory is a directory which is located within another directory.


3 Answers

for dir in $(ls); do
  mkdir "$dir/new-dir"
done
like image 109
Ju Liu Avatar answered Nov 15 '22 09:11

Ju Liu


find . -type d | xargs -I "{x}" mkdir "{x}"/new-dir

If you want to reduce it to the first level of directories use

find . -maxdepth 1 -type d | xargs -I "{x}" mkdir "{x}"/new-dir
like image 40
martinw Avatar answered Nov 15 '22 11:11

martinw


Amazing that this question never obtained a sane answer:

shopt -s nullglob
for i in */; do
    mkdir -- "${i}newdir"
done
  • This is 100% safe regarding funny symbols in filenames (spaces, wildcards, etc.).
  • The shopt -s nullglob so that the glob expands to nothing if there are no matches.
  • The -- in mkdir to mark the end of options (if there's a directory with a name starting with a hyphen, doesn't confuse mkdir trying to interpret it as an option).

This silently ignores the hidden directories. If you need to perform this operation on hidden directories, just replace the line shopt -s nullglob by the following:

shopt -s nullglob dotglob

The dotglob so that the globs also consider hidden files/directories.

If you want only one invocation of mkdir:

shopt -s nullglob
dirs=( */ )
mkdir -- "${dirs[@]/%/newdir}"
like image 24
gniourf_gniourf Avatar answered Nov 15 '22 09:11

gniourf_gniourf