DEV Community

Tek Kshetri
Tek Kshetri

Posted on

Generate files and folder structures of your code

I recently found a cool way to generate the file and folder structure inside your root project directory. In order to generate the folder structure, you need to follow following steps,

1. Download tree package

If you are in mac, type following code in your terminal,

brew install tree
Enter fullscreen mode Exit fullscreen mode

If you are in ubuntu, type following code in your terminal,

sudo apt install tree
Enter fullscreen mode Exit fullscreen mode

2. Navigate to the root directory

cd ~/Downloads/my-project
Enter fullscreen mode Exit fullscreen mode

Make sure to change the path.

3. Explore tree command

If you want to generate the files and folder structure in your working directory, just type tree command in terminal and it will print out the files and folders in proper structure,

tree
Enter fullscreen mode Exit fullscreen mode

But, most of the time, our project might contain some of the unnecessary things such as, node_modules, python_venv etc. In that case, you might want to avoid those folders or files. In order to avoid those, simply wright the following code,

find . -type f -not -path '*/\.*' | grep -v -F -f .gitignore | cut -c 3- | tree --fromfile --prune
Enter fullscreen mode Exit fullscreen mode

Let me explain the code for you,

  • find . -type f -not -path '*/\.*': This command recursively finds all the files (-type f) in the current directory (.) and its subdirectories. The -not -path '*/\.*' part excludes hidden files such as .git.

  • grep -v -F -f .gitignore: This command filters out the files and directories listed in the .gitignore file.

  • The cut -c 3- command removes the first two characters from each line of input, effectively removing the "./" prefix in each path.

  • tree --fromfile --prune: This command reads the file and directory structure from the output of the previous commands and displays it using the tree command. The --prune option excludes the empty directories from the output.

I got the following result from above script:

.
├── __init__.py
├── file1.ipynb
├── file2.ipynb
├── requirements.txt
├── script_json
│   ├── test1.json
│   └── test2.json
├── version1.ipynb
└── version2.ipynb

Enter fullscreen mode Exit fullscreen mode

I hope this post is informative for you. If you like this blog, please support me by subscribing to my YouTube channel: https://www.youtube.com/c/iamtekson

Top comments (1)

Collapse
 
bm_sadi_hcmc profile image
BM Sadi

awesome work. thank you.