I want to count the number of lines in
example.txt and append the result to the end of this file. How can I do this?
wc -l > example.txt
As you know, wc -l by default, includes the result number plus the file name. If for some reason it is better to have literally just the result number only, try this:
wc -l example.txt | cut -d' ' -f1 >> example.txt
So if example.txt started with only 3 lines, eg:
a b c
After you run the above, use
tail to look at the last lines (in this case very few lines so it views the entire file) you see:
$ tail example.txt a b c 3
wc -l example.txtwhich gives default result line count and file name, eg
cutcommand helps extract "fields" from lines
-dis to set delimiter/field separator, which we specify is
' ', a space.
-f1means choose the first field, so given
3is the first field
>>appends, so it saves the result
3, to end of the file
The following script adds the line count to the end of the file if it is not already there, but deletes and replaces it if there is already a line count.
This allows you to run this script every time your file(s) are edited without adding multiple 'Line count:' lines.
#! /bin/bash count=$(wc -l "$1" | cut -d' ' -f1) tail -1 "$1" | grep -q '^Line count: ' if [ $? ]; then count=$(( $count - 1 )) # don't count the 'Line count' line sed -i -e '$ d' "$1" echo "Line count: $count" >> "$1" else echo "Line count: $count" >> "$1" fi