Linux, OpenSource, Programming And Hacks

Aug 25, 2015

Linux wc command: count characters, words, lines of a file

Aug 25, 2015
The wc command in unix/linux is used to print the number of characters, words, bytes and newlines of files or standard input.


Usage and examples:

Here we will test the commands on a file named song.txt, which contains some lyrics. To view the contents of song.txt lets use the cat command
$ cat song.txt
Master, master, where's the dreams that I've been after?
Master, master, you promised only lies
Laughter, laughter, all I hear or see is laughter
Laughter, laughter, laughing at my cries
Fix Me

1. Display Number of Bytes

Enter wc command with  -c  option to print no. of bytes in a file.
$ wc -c song.txt
194 song.txt

2. Display Number of Words

Enter wc followed with -w option to print the no. of words in a file
$ wc -w song.txt
32 song.txt

3. Display Number of Characters

Enter wc with -m option to print no. of characters in a file
$ wc -m song.txt
194 song.txt

4. Display Number of New lines

Enter wc with -l option to print the no. of new lines in the file.
$ wc -l song.txt
5 filename

5. Display Length of the longest line

Enter wc with -L option to print the no. of characters in the longest line of the file
$ wc -L song.txt
56 song.txt

6. Display All

Enter wc and filename without any option will show in the following column order: 1st column- newlines count, 2nd column- words count and 3rd column- character count.
$ wc song.txt
 5  32 194 song.txt

$ wc song.txt song2.txt #for multiple files
 5  32 194 song.txt
 10  57 297 song2.txt
 15  89 491 total

7. Display counts for standard input

Just entering the wc command waits for you to enter some text and after you have written the text press ctrl+d to end writing. wc counts number of lines, words and bytes
$ wc
welcome to TechInfected      0       3      23
the newline count is 0 because there is only one line and no newlines.

No comments:

Post a Comment