iamr00t
iamr00t

Reputation: 33

Shell Script to Display Directories and Contents in a List

Shell Script to Display Directories and Contents in a List

I have a folder called Projects and within that folder I have 5 projects. For the sake of this question I'm just going to keep it simple and say that they are labeled like: (Project1, Project2, etc...). When I run ls on the folder I get this: (re-labeled for simplicity):

Project1  Project2  Project3  Project4  Project5

Within these 5 folders, I have 1 .txt file in each directory. How can I create a shell script to list the contents of the folders like this:

1. Project1
     > readme.txt

2. Project2
     > readme.txt

3. Project3
     > readme.txt

4. Project4
     > readme.txt

5. Project5
     > readme.txt

So basically list the directories with a counter and list the sub-directories under the parent folders.

P.S. The symbol used under the folder name doesn't have to be a '>' , I just used that so it didn't create bullets when using '-'.

Upvotes: 0

Views: 781

Answers (2)

Kusalananda
Kusalananda

Reputation: 15603

#!/bin/sh

topdir='/tmp/shell-bash.DmgIjp5V'
readme='README.txt'
i=0

for pathname in "$topdir"/*/"$readme"; do
        project="$(basename "$(dirname "$pathname")")"
        printf '%d. %s\n\t- %s\n\n' "$(( ++i ))" "$project" "$readme"
done

Test setup:

bash-4.4$ mkdir Project{1..5}
bash-4.4$ touch Project{1..5}/README.txt

Running it:

bash-4.4$ sh script.sh
1. Project1
        - README.txt

2. Project2
        - README.txt

3. Project3
        - README.txt

4. Project4
        - README.txt

5. Project5
        - README.txt

Details:

The script simply looks for all README.txt files two levels below $topdir (this would be your Projects directory) and iterates over these.

The project variable will hold the name of the project directory under $topdir.

The printf statement formats and outputs the data according to you specification.

I'm using basename and dirname here, but some people thinks using variable substitutions are better (it's certainly faster). However, I'm keeping them in for clarity.

Upvotes: 0

Kyle Miller
Kyle Miller

Reputation: 126

The easiest way to display the information like you are asking would be to use the $ tree command from the directory that you want to see all the contents in a hierarchical form.

if not already installed (if using linux it should be)

$ sudo apt update
$ sudo apt upgrade
$ sudo apt install tree

if using mac

$ brew update
$ brew upgrade
$ brew install tree 

This command will display all directories, sub directories below the dir you run the tree command from

hope this helps

Upvotes: 1

Related Questions