shell script to count number of words

Shell Script to Count Number of Words in File

Sometimes you may need to count the number of words in a file. You can easily do this using wc command. In this article, we will look at how to create a shell script to count number of words in File.


Shell Script to Count Number of Words in File

Here are the steps to create shell script to count number of words in file.


1. Create Shell Script

Open terminal and run the following command to create empty shell script file.

$ sudo vi word_count.sh


2. Add shell commands to count words

Add the following lines to your shell script.

#!/bin/bash
word_count=$( wc -w < $1)
echo $word_count

In the above code, the first line specifies the execution shell environment. The next line gets the word count from file, that we accept as command line argument. The third line echoes the word count.


3. Make shell script executable

Run the following command to make it executable.

$ sudo chmod +x word_count.sh


4. Test shell script

Test the shell script with a few files on your system

$ sudo ./word_count.sh /home/data.txt
134

$ sudo ./word_count.sh /home/ubuntu/test.txt
215

That’s it. In this article, we have created a simple shell script to help you easily get word count from any file on your system. You can modify it as per your requirement.

Also read:

How to Enable & Disable Services in Linux
NGINX Alias vs Root
How to Download File to Directory using wget
How to Create Disk Image from Directory
Shell Script to Concatenate Strings

Leave a Reply

Your email address will not be published.