Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find word count using wc and assign to a variable

Tags:

unix

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
like image 679
ShravanM Avatar asked Sep 22 '14 18:09

ShravanM


People also ask

Which option counts the number of words in file with wc command?

The following are the options and usage provided by the command. wc -l : Prints the number of lines in a file. wc -w : prints the number of words in a file. wc -c : Displays the count of bytes in a file.

How do you store a word count in a variable in Unix?

Create a variable to store the file path. Use wc –lines command to count the number of lines. Use wc –word command to count the number of words.

How do you use wc?

Use the wc command to count the number of lines, words, and bytes in the files specified by the File parameter. If a file is not specified for the File parameter, standard input is used. The command writes the results to standard output and keeps a total count for all named files.


2 Answers

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)
like image 55
P.P Avatar answered Sep 22 '22 23:09

P.P


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

like image 27
Ryan Kuster Avatar answered Sep 26 '22 23:09

Ryan Kuster