ShravanM
ShravanM

Reputation: 323

Find word count using wc and assign to a variable

i want the word count wc -w value be assigned to a variable

i've tried something like this, but i'm getting error, what is wrong?

winget="this is the first line"

wdCount=$winget | wc -w

echo $wdCount

Upvotes: 5

Views: 20476

Answers (3)

Sushovan Mishra
Sushovan Mishra

Reputation: 23

You can use this to store the word count in variable:

word_count=$(wc -w filename.txt | awk -F ' ' '{print $1}'

Upvotes: 1

Ryan Kuster
Ryan Kuster

Reputation: 41

You can pass word count without the filename using the following:

num_of_lines=$(< "$file" wc -w)

See https://unix.stackexchange.com/a/126999/320461

Upvotes: 2

P.P
P.P

Reputation: 121407

You need to $(...) to assign the result:

wdCount=$(echo $winget | wc -w)

Or you could also avoid echo by using here-document:

wdCount=$(wc -w <<<$winget)

Upvotes: 5

Related Questions