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?

I tried:

wc -l > example.txt
  • You notice that each time you'll do it, number of line increase ? – Archemar Sep 27 '15 at 19:51
wc -l example.txt >> example.txt
  • This will include file name, not the number of lines only. – cuonglm Sep 28 '15 at 15:55

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

Explanation

  • you already know wc -l example.txt which gives default result line count and file name, eg 3 example.txt
  • the cut command helps extract "fields" from lines
  • the -d is to set delimiter/field separator, which we specify is ' ' , a space.
  • the -f1 means choose the first field, so given wc output was 3 example.txt the 3 is the first field
  • >> appends, so it saves the result 3, to end of the file example.txt

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

To append only the amount of lines, you can try this

$ cat example.txt | wc -l >> example.txt

This will only display the total amount of lines in the file

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.