Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In bash, how do I count the number of lines in a variable?

Tags:

string

bash

I have a variable which has a string stored in it and need to check if it has lines in it:

var=`ls "$sdir" | grep "$input"` 

pseudo-code:

while [ ! $var's number of lines -eq 1 ]   do something 

That's my idea on how to check it. echo $var | wc -l doesn't work - it always says 1, even though it has 3.

echo -e doesn't work as well.

like image 506
krack krackerz Avatar asked Jun 11 '11 07:06

krack krackerz


People also ask

How do I count lines in bash?

wc. The wc command is used to find the number of lines, characters, words, and bytes of a file. To find the number of lines using wc, we add the -l option. This will give us the total number of lines and the name of the file.

How do I count the number of lines in a file shell?

Using “wc -l” There are several ways to count lines in a file. But one of the easiest and widely used way is to use “wc -l”. The wc utility displays the number of lines, words, and bytes contained in each input file, or standard input (if no file is specified) to the standard output.

How do I count characters in a variable bash?

you can use wc to count the number of characters in the file wc -m filename.

How do I count lines in terminal?

The most easiest way to count the number of lines, words, and characters in text file is to use the Linux command “wc” in terminal. The command “wc” basically means “word count” and with different optional parameters one can use it to count the number of lines, words, and characters in a text file.


1 Answers

Quotes matter.

echo "$var" | wc -l 
like image 86
Ignacio Vazquez-Abrams Avatar answered Oct 07 '22 12:10

Ignacio Vazquez-Abrams