Let’s continue to work on the script that prints the directory structure tree. At the end of the last exercise, our script was able to print all nested subdirectories and files under a parent directory. In this exercise, we will add to the script. We’ll use the grep
command to filter this output to only include subdirectories, not files, and format it to better match a tree-like structure using sed
.
The left side of the image below shows what our script’s output looks like now. The right side is what it will look like after adding the grep
and sed
commands.
As you can see, the directory structure is a lot easier to follow after we will use the
sed
command to:
- Remove colons
- Use dashes (
-
) to differentiate between directory and sub-directory - Indent to the right by three spaces
- Replace the first dash with a vertical bar (
|
)
Let’s make the output look nice!
Instructions
In our current output, the lines for directories end with the character :
while the lines with the files do not. We can use grep
to keep only the lines where the last character is “:”.
In the line of the script where we currently have ls -R
, let’s add on by piping |
the output from the ls -R
to grep ":$"
. ( $
is a regex symbol that matches characters at the end of a string).
Click the Run button when you are done.
Run the script with ~
(the home directory) as input to see the difference the grep
command has made!
Now that we just have the subdirectories listed, we can use sed
to transform the output to remove colons and include indents and dashes. Add a pipe after the ls -R | grep ":$"
statement and attach the command
sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/ /' -e 's/-/|/'
Pro tip: To help with readability, you can use a backslash \
to break the long line into two.
Click the Run button when you are done.
Drop down here to see an explanation of the `sed` expressions
The first expression, 's/:$//'
, removes all colons at the end of each line.
The second expresion, 's/[^-][^\/]*\//--/g'
, essentially replaces all /
with --
.
The third expresion, 's/^/ /'
, indents each line by adding three spaces to the beginning.
The fourth expresion, 's/-/|/'
, replaces the first dash -
of each line with |
.
For additional spacing, add an echo
command with no arguments to the beginning and the end of the script. In other words, echo
should print an empty string.
Click the Run button when you are done.
And we’re done! Run the script with ~
as input to see the results of your hard work!