results of wc as variables

719016 picture 719016 · Aug 19, 2011 · Viewed 62.1k times · Source

I would like to use the lines coming from 'wc' as variables. For example:

echo 'foo bar' > file.txt
echo 'blah blah blah' >> file.txt
wc file.txt

2  5 23 file.txt

I would like to have something like $lines, $words and $characters associated to the values 2, 5, and 23. How can I do that in bash?

Answer

Arnaud Le Blanc picture Arnaud Le Blanc · Aug 19, 2011

In pure bash: (no awk)

a=($(wc file.txt))
lines=${a[0]}
words=${a[1]}
chars=${a[2]}

This works by using bash's arrays. a=(1 2 3) creates an array with elements 1, 2 and 3. We can then access separate elements with the ${a[indice]} syntax.

Alternative: (based on gonvaled solution)

read lines words chars <<< $(wc x)

Or in sh:

a=$(wc file.txt)
lines=$(echo $a|cut -d' ' -f1)
words=$(echo $a|cut -d' ' -f2)
chars=$(echo $a|cut -d' ' -f3)