How to print tree directory structure in linux/unix

In the daily development process, we often need to use linux commands to print the code directory tree structure or the system directory tree structure.

This liunx tutorial mainly teaches you to print the directory tree structure using linux commands.

Let’s see how to use Linux commands to print the tree directory structure of the code.

There are two ways for Linux to print the tree structure of the file system: one is through the linux tree command, and the other is through the combined command of linux find, awk and sed commands.

Print the tree directory structure using the linux tree command

Here to test the wordpress blog source code.

➜  wordpress tree -dL 1
.
├── wp-admin
├── wp-content
└── wp-includes
  • -d
    List directories only.
  • -L level
    Max display depth of the directory tree.

➜  wordpress tree -dL 2
.
├── wp-admin
│   ├── css
│   ├── images
│   ├── includes
│   ...
├── wp-content
│   ├── ew_backup
│   ├── languages
│   ├── plugins
│   ...
└── wp-includes
    ├── ID3
    ├── IXR
    ├── Requests
    ...

Print tree directory structure using command combinations

➜ find . -type d | awk -F'/' '{if(NF==2){print "|-- " $2 }else if(NF==3) {print "|  |--" $3}}'

This command, like the tree command, is a directory tree structure with a print depth of 2.

|-- wp-admin
|  |--css
|  |--images
|  |--js
|  ...
|-- wp-includes
|  |--blocks
|  |--ID3
|  |--SimplePie
|  ...
|-- wp-content
|  |--upgrade
|  |--wflogs
|  |--plugins
|  ...

Command explanation:

First, list all directory structures under the current directory.

➜ find . -type d

.
./wp-admin
./wp-admin/css
./wp-admin/css/colors
...
./wp-includes
./wp-includes/blocks
./wp-includes/ID3
...

Then, use the awk command to separate them according to “/”.

awk -F'/' '{
	if(NF==2) {
		print "|-- " $2
	}else if(NF==3) {
		print "|  |--" $3
	}
}'

If the number of separated fields is 2, which represents the root directory of the tree structure, print “|–“;

if the number of separated fields is 3, it represents the leaf nodes of the tree structure , Print “| |–“

ok, so you can print a two-level tree directory structure.

What if we need to print a multilevel tree directory structure? Is it necessary to write multiple if else?

Not!!!

How to print a multilevel tree directory structure using the linux find and awk combined commands

find . -type d | awk -F'/' '{ 
	depth=3;
	offset=2;
	str="|  ";
	path="";
	if(NF >= 2 && NF < depth + offset) {
		while(offset < NF) {
			path = path "|  ";
			offset ++;
		}
		print path "|-- "$NF;
	}
}'

depth: Number of levels to print

print tree directory structure

One Comment

Add a Comment

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