how to count the number of lines in a variable in a shell script

advertisements

Having some trouble here. I want to capture output from ls command into variable. Then later use that variable and count the number of lines in it. I've tried a few variations

This works, but then if there are NO .txt files, it says the count is 1:

testVar=`ls -1 *.txt`
count=`wc -l <<< $testVar`
echo '$count'

This works for when there are no .txt files, but the count comes up short by 1 when there are .txt files:

testVar=`ls -1 *.txt`
count=`printf '$testVar' | wc -l`
echo '$count'

This variation also says the count is 1 when NO .txt files exist:

testVar=`ls -1 *.txt`
count=`echo '$testVar' | wc -l`
echo '$count'

Edit: I should mention this is korn shell.


The correct approach is to use an array.

# Use ~(N) so that if the match fails, the array is empty instead
# of containing the pattern itself as the single entry.
testVar=( ~(N)*.txt )
count=${#testVar[@]}