Bash: How to get the wordcount of a file and insert it into the file itself?

I am not an experienced bash user. I want to get the number of words in a file and insert it back into the file for use as an identifier.

First, I initialize the variable wordcnt

as zero.

wordcnt=0;

      

Then I run the code

for file in *.txt; do 
wordcnt=$((wc -w < $file));
echo "<field name='wordcount'>$wordcnt</field>" >> $file;
done

      

As a result, I get

-bash: wc -w < file.txt: syntax error: invalid arithmetic operator 
(error token is ".txt")

      

I don't think I can apply word count to a variable the wordcnt

way I do.

How can I apply word count to a variable and then insert it into a file?

+3


source to share


1 answer


You need to drop an extra pair of partners:

for file in *.txt; do 
    wordcnt=$(wc -w < $file);
    echo "<field name='wordcount'>$wordcnt</field>" >> $file;
done

      



Command substitution $(..)

will write the output wc

and assign it to a variable wordcnt

.

+5


source







All Articles