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?
There are other solutions but a simple one which I usually use is to put the output of
wcin a temporary file, and then read from there:The advantage of this method is that you do not need to create several
awkprocesses, one for each variable. The disadvantage is that you need a temporary file, which you should delete afterwards.Be careful: this does not work:
The problem is that piping to
readcreates another process, and the variables are updated there, so they are not accessible in the calling shell.Edit: adding solution by arnaud576875:
Works without writing to a file (and do not have pipe problem). It is bash specific.
From the bash manual:
The key is the “word is expanded” bit.