aprilduck
aprilduck

Reputation: 79

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.

Upvotes: 1

Views: 48

Answers (2)

Ed Morton
Ed Morton

Reputation: 203674

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

Upvotes: 3

Cyrus
Cyrus

Reputation: 88654

Try this with tree and GNU sed:

tree -F coreutils-8.9 | sed -r 's|── (.*)/$|── DIR: \1|'

Output (example):

coreutils-8.9
├── ABOUT-NLS
├── bootstrap.conf
├── DIR: build-aux
│   ├── announce-gen*
│   ├── arg-nonnull.h
│   └── ylwrap*
├── cfg.mk
├── ChangeLog
├── DIR: doc
│   ├── ChangeLog-2007
│   └── constants.texi
└── TODO

I assume that the file names don't contain "── ".

Upvotes: 4

Related Questions