How to count words in a file without using wc command ?

To count number of words in a file, we can either use wc command, or use a loop or can use extended grep command.

Lets see the easiest two approaches to count words in a file.

1. Using wc command.

[root@ngelinux ~]# wc -w test.txt 
5 test.txt
[root@ngelinux ~]# 

2. Using extended grep command.
In this trick, we will take all words of the file inside an array.
And then count number of elements in the array to get total number of words.

### Take all words in array named count
[root@nglinux ~]#count=( $(grep -E '\w+' test.txt) )

### Get number of array elements i.e. total words
[root@nglinux ~]#echo ${#count[@]}
5
[root@nglinux ~]#

### Get first i.e. 0th element of the array
[root@nglinux ~]#echo $count
dog

### Get second element from the array i.e. second word of the file.
[root@nglinux ~]#echo ${count[1]}
cat

Leave a Reply

avatar
  Subscribe  
Notify of