Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing output and counting its lines

Tags:

find

bash

wc

I'd like to run a find command and then count the lines of the output as well as give out the output of the result. My straight-forward approach was this:

output=$(find ...)
lines=$(echo "$output" | wc -l)
echo "$output"

But unfortunately using echo to pipe this into wc adds a newline, so even if the find did not find anything (zero lines of output), that wc is giving out 1 (for the newline which the echo appended.

I changed the echo to a printf to prevent appending the newline to the output but then also a one-line output of find like var/ was without a newline, and hence the wc gave out 0.

The problem is in the capturing of the output ($(...)). It strips trailing newlines which in my case are relevant.

Can this be prevented somehow?

Is there a completely different approach on my original task?

like image 244
Alfe Avatar asked Nov 24 '25 15:11

Alfe


2 Answers

A simple workaround that would occur to mind would be to check if the string is empty:

[ -z "$output" ] && count=0 || count=$(wc -l <<< "$output")

Now count would be 0 if find didn't produce any output else it would contain the number of lines in the output.

like image 69
devnull Avatar answered Nov 27 '25 05:11

devnull


Counting new lines after storing find's output in a variable is always going to be problematic in case your file names contain spaces or new lines.

I would suggest using find like this (to count all *.txt files and print them)

output=
c=0

while read -d ''; do 
    ((c++))
    output+="$REPLY"$'\n'
done < <(find . -name "*.txt" -print0)

echo "c=$c"
echo "output=$output"

PS: This will also take care of new lines/spaces in file names.

like image 43
anubhava Avatar answered Nov 27 '25 05:11

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!