Two small tools help you measure and label text: wc counts it, and nl numbers its lines.
wc: word count
With no options, wc prints lines, words, bytes and the file name.
$ cat poem.txt
roses are red
violets are blue
$ wc poem.txt
3 6 32 poem.txtSpacing between the columns varies.
Pick one count
-llines-wwords-cbytes-mcharacters
$ wc -l poem.txt
3 poem.txt-c and -m give the same result for plain ASCII. With UTF-8 text, one character can take several bytes, so the numbers differ.
wc -l really counts newline characters. A last line with no newline is not counted.
$ printf 'one\ntwo' | wc -l
1In pipelines, wc -l answers "how many?":
$ ls | wc -lnl: number lines
$ nl poem.txt
1 roses are red
2 violets are blueBy default nl numbers only non-empty lines.
Use -b a to number every line:
$ nl -b a poem.txt
1 roses are red
2
3 violets are blueYou can adjust the layout with -w for the number width and -s for the text after the number.
$ nl -w 2 -s '. ' poem.txt
1. roses are red
2. violets are bluecat -n is another way to number all lines. nl only changes what is printed, not the file.
Practise in the streams and text lab.
Try it
- Run
wc /etc/passwd. - Count accounts with
wc -l < /etc/passwd. - Compare
echo รฉ | wc -candecho รฉ | wc -min a UTF-8 terminal. - Run
nlandnl -b aon a file with blank lines.
Check your understanding
wc and nl
All 5 sections ยท no timer
Unlimited retries
Questions from every section are combined into one assessment. Answer them all correctly to complete the article.
Your completion saves in this browser. Sign in to sync it to your account.