Skip to content

Linux Foundations / Find your way around Linux ยท Step 45 of 63

Lesson: wc and nlSwitch
โ† Linux Foundations

Shell and files

wc and nl

Learn to count lines, words and bytes with wc and to number lines with nl.

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.txt

Spacing between the columns varies.

Pick one count

  • -l lines
  • -w words
  • -c bytes
  • -m characters
$ 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
1

In pipelines, wc -l answers "how many?":

$ ls | wc -l

nl: number lines

$ nl poem.txt
     1	roses are red
       
     2	violets are blue

By 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 blue

You 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 blue

cat -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

  1. Run wc /etc/passwd.
  2. Count accounts with wc -l < /etc/passwd.
  3. Compare echo รฉ | wc -c and echo รฉ | wc -m in a UTF-8 terminal.
  4. Run nl and nl -b a on 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.