Reputation: 65
I have a variable containing some command output, and I want to count the number of lines in that output. I am trying to do this using pure bash (instead of piping to wc like in this question).
The best I have come up with seems kind of cumbersome:
function count_lines() {
num_lines=0
while IFS='' read -r line; do
((num_lines++))
done <<< "$1"
echo "$num_lines"
}
count_lines "$my_var"
Is there a cleaner or shorter way to do this?
Upvotes: 2
Views: 1223
Reputation: 1242
Another possible solution I came up with:
export x=0;while read i;do export x=$(($x+1));done < /path/to/your/file;echo $x
Upvotes: 0
Reputation: 531165
count_lines () (
IFS=$'\n'
set -f
set -- $1
echo $#
)
Some tricks used:
The function is defined using a subshell instead of a command group to localize the change to IFS
and the -f
shell option. (You could be less fancy and use local IFS=$'\n'
instead, and running set +f
at the end of the function).
Disable filename generation to avoid any metacharacters in the argument from expanding and interfering with the line count.
Once IFS
is changed, set the positional parameters for the function using unquoted parameter expansion for the argument.
Finally, output the number of positional parameters; there is one per line in the original argument.
Upvotes: 4
Reputation: 116730
IFS=$'\n'
set -f
x=( $variable )
Now ${#x[@]} will contain the number of 'lines'. (Use "set +f" to undo "set -f".)
Upvotes: 1