aprilduck aprilduck - 7 months ago 11
Bash Question

List directories and files in a tree structure

I'm trying to list directories and files contained within them in the following way:

DIR: name1
file1
file2
file3
DIR: name2
file4
file5
file6
DIR: name3
file7


So far, I've come up with a way to get a tree structure using
find
and
sed
, like this:

find . | sed -e "s/[^-][^\/]*\// |/g"


I don't know how to distinguish between files and directories to be able to add
DIR:
in front of the names of the directories.

Answer

If you don't have tree you can use GNU find to identify directories vs files:

$ find . -mindepth 1 -printf '%y %p\n'
d ./dir1
d ./dir1/dir2
f ./dir1/dir2/fileA
d ./dir1/dir3
f ./dir1/fileC
f ./fileB

and then parse the output with awk to create the indenting, etc.

$ find . -mindepth 1 -printf '%y %p\n' |
    awk '$1=="d"{sub(/.*\//,"&DIR: ")} {gsub(/[^\/]*\//,"  ")} 1'
  DIR: dir1
    DIR: dir2
      fileA
    DIR: dir3
    fileC
  fileB