On a repository with some JavaScript code, I started out with named component and utility files. Something like this:

- components/
  - Foo.js
- hooks/
  - useFoo.js

Given we also want to have file-specific documentation, and in future maybe styles, I wanted to change the name/location of each of the files from being a named file to being a generix index.js file in a new folder with the current name.

So we would have this, in the end:

- components/
  - Foo/
    - index.js
- hooks/
  - useFoo/
    - index.js

Surely, this should be easy to do programmatically, right? Right.

Making sure you are in src, here is how I did it:

for f in **/*.js; do dir="${f%.*}" && mkdir "$dir" && mv "$f" "${dir}/index.js"; done

A little more readable:

for f in **/*.js
  mkdir "$dir"
  mv "$f" "${dir}/index.js"

Maybe that’s useful for anyone, and if only future-me.

Please note that I did not have file names with multiple dots, for example, Foo.test.js. If you do, you might have to slightly change how to trim leading/trailing parts of the file name (e.g., using dir="${f%%.*}" and "${dir}/index.${f#*.}").

Leave a Reply

Your email address will not be published. Required fields are marked *