user3060684
user3060684

Reputation: 93

Using find and grep to fill an array

In bash I am trying to produce an array of path-names to files with zero size.
I am using

find . -size 0

which gives me the list of files and their paths. So the Output is:

./001/013/fileA
./001/014/fileB
./002/077/fileA

Now I want an array that I can loop through, like this:

(001/013 001/014 002/077)

I tried this:

folderlist=($(find . -size 0 | grep '\<[0-9][0-9][0-9][/][0-9][0-9][0-9]\>' ))
for i in "${folderlist[@]}"
do
    echo $i
done

But the output is empty.

What am I missing?

Thanks a lot!

Upvotes: 3

Views: 171

Answers (2)

Kannan Mohan
Kannan Mohan

Reputation: 1850

You can used dirname to reliably get the directory path.

folderlist=($(find . -size 0 -print0|xargs -0 -I% dirname %))
for i in "${folderlist[@]}"
do
    echo $i
done

Upvotes: 1

anubhava
anubhava

Reputation: 785781

To strip just file names from find output you can use:

folderlist=($(find . -size 0 -exec bash -c 'echo "${1%/*}"' - {} \;))

Or to loop through those entries:

while read -r f; do
   echo "Processing: $f"
done < <(find . -size 0 -exec bash -c 'echo "${1%/*}"' - {} \;)

Upvotes: 2

Related Questions