Sahil
Sahil

Reputation: 9478

how to list files using LS command of the sub directories?

I have a file strucuture like this:

a
----1
----2
----3

b
----1
----2
----3

I need to count the files of level 2 with level 1 being a,b directories, so is there any way of doing it? getting files of specific level?

I am a naive shell programmer, all I have used so far ls | wc-l, but it will return 2 in this case

Upvotes: 0

Views: 450

Answers (4)

glenn jackman
glenn jackman

Reputation: 246807

Assuming bash or similar shell, use globbing and an array

$ ls -R
.:
a  b

./a:
1  2  3

./b:
4  5  6
$ level2=(*/*)
$ echo "num files at level 2: ${#level2[@]}"
num files at level 2: 6

Upvotes: 1

anishsane
anishsane

Reputation: 20980

Yet another way...

L2FilesDirs=`ls -d */* | wc -l`
L2Dirs=`ls -d */*/ | wc -l`

L2OnlyFiles=$(( $L2FilesDirs - $L2Dirs ))

Upvotes: 2

Jens
Jens

Reputation: 72649

Some find(1) executables support the mindepth and maxdepth options (they are sadly not POSIX, but if you use GNU tools like on Linux or Cygwin):

find . -mindepth 2 -maxdepth 2

which lists all file system objects in all subdirectories (except . and .. entries, which is probably what you want anyway).

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 361615

There are a couple of options.

  1. Count all files recursively:

    find . -type f | wc -l
    
  2. Count files under a and b only:

    find a b -type f | wc -l
    
  3. Count all objects at depth 2:

    find . -mindepth 2 -maxdepth 2 | wc -l
    find a b -mindepth 1 -maxdepth 1 | wc -l
    

Upvotes: 1

Related Questions