Reputation: 195
I am trying to get a list of all files within the directories and sub-directories but without using find
or doing it recursively.
I need to find a way to do it using ls
, grep
and sed
.
I can't seem to find a solution that doesn't just use find
.
EDIT:
I am trying to basically find a way to count all the files and directories within one directory. I can't use recursive functions, but I can use iterative statements, such as for loops and if statements.
I have found a way to do this using a for loop, but this only searches within the subdirectories, and not within folders in those subdirectories. In other words the depth is only 2. I need it to search throughout. Again I cannot use the find
command.
Hopefully this helps to clear out any issues.
This is what I have so far:
a=0
b=0
for i in $( ls ); do
if [ -d "$i" ] ; then
c=$(pwd)
cd $i
a=$(($a + $(ls -l | grep -e "^-" | wc -l)))
b=$(($b + $(ls -l | grep -e "^d" | wc -l)))
cd $c
fi
done
echo "Number of files: $a"
echo "Number of directories: $b"
Upvotes: 0
Views: 956
Reputation: 17725
The simplest way to execute iteratively a recursive task is to use some kind of stack (in this case an array):
DIR_COUNT=0
FILE_COUNT=0
# use an array as stack, initialized with the root dir
STACK=(".")
# loop until the stack is empty
while [ ${#STACK[@]} -gt 0 ] ; do
# get the next dir to process (first element of the array)
DIR=${STACK[0]}
# remove it from the stack (replace the stack with itself minus the first element)
STACK=(${STACK[@]:1})
for i in $(ls $DIR); do
if [ -d "$DIR/$i" ] ; then
((DIR_COUNT++))
# add the directory to process it later
STACK+=($DIR/$i)
else
((FILE_COUNT++))
fi
done
done
echo Number of files: $FILE_COUNT
echo Number of directories: $DIR_COUNT
This will probably only work with bash
, I hope this is ok.
Upvotes: 0
Reputation: 6641
You probably want to avoid explicit recursion. ls
was built just for that and has built-in recursion, use:
ls -R
Upvotes: 1