ithil
ithil

Reputation: 1758

Create a folder inside other folders using bash

I have a long list of folders that are siblings to each other, they all start with "0" and are numerically named (001, 002, 003...) but names are not only numerical and are not correlative (for example I have 0010_foo, 0032_bar, 0150_baz, etc). I need to create a new folder (js) inside each of the folders on my list. I'd like to do it recursively using the command line.

I've tried:

$ cd path/to/my/root/folder
$ find 0* -type d -exec mkdir js {} \;

But I get an error for each attempt: "mkdir: js: file exists". No need to say there's no directory named js inside my folders but they are files with .js extension.

Where is the error in my command and how can I fix it? Thanks!

Upvotes: 1

Views: 1072

Answers (3)

chepner
chepner

Reputation: 531075

mkdir js {} tries to create two directories; you want mkdir {}/js.

To prevent find from repeatedly finding your new directory, ignore any directory named js.

find 0* ! -path '*/js' -type d -exec mkdir {}/js \;

Upvotes: 2

gniourf_gniourf
gniourf_gniourf

Reputation: 46823

(Why your find command doesn't work is already explained in bishop's (now deleted) answer — I'm only giving an alternative to find).

You can replace find by a shell for loop as so:

for i in 0*/; do mkdir "$i"js; done

Upvotes: 2

bishop
bishop

Reputation: 39374

I'm not 100% sure of your directory structure after your edit, but give this a whirl:

cd /path/to/my/root/folder
find . -maxdepth 1 ! -path . -type d -exec mkdir -p {}/js \;

Seems to work ok:

$ cd /path/to/my/root/folder
$ tree
.
├── 001
│   └── js
└── 002
$ find . -maxdepth 1 ! -path . -type d -exec mkdir -p {}/js \;
.
├── 001
│   └── js
└── 002
    └── js

What this find does: In the current directory (.), it finds sub-directories (-type d) -- except the current directory itself (! -path .) and any sub-sub-directories (-maxdepth 1). In those found directories, it creates the desired sub-directory (-exec ...). The mkdir -p part creates the directory and silences any errors about parents not existing. find replaces the {} part with the actual directory it found.

Upvotes: 1

Related Questions