Often Linux developers and system administrators need to count number of words in file. You can easily do this using wc command. But if you want to automate it, then it is advisable to create a shell script for it. In this article, we will learn how to create shell script to count number of words in file.
Shell Script to Count Number of Words in File
Here is how to create shell script to count number of words in file.
1. Create Shell Script
Run the following command to create empty shell script.
$ vi word_count.sh
2. Add Shell Script
Add the following shell script to determine the number of words in file.
#!/bin/bash
word_count=$( wc -w < $1)
echo $word_count
Save and close the file. In the above code, the first line is the execution environment. The next line counts the number of words using wc command. The file path is received as command line argument $1. The third line displays the word count.
3. Make Shell Script Executable
Next, run the chmod command to make the shell script executable.
$ sudo chmod +x word_count.sh
4. Test Shell Script
Test shell script with some of the files on your system.
$ sudo ./word_count.sh /home/data.txt
134
$ sudo ./word_count.sh /home/ubuntu/test.txt
215
In this article, we have learnt how to write shell script to determine number of words in Linux. You can customize it as per your requirement.
Also read:
How to Create Disk Image from Directory
How to Download File to Directory in Wget
Shell Script to Concatenate Strings
How to Run Shell Script As Background Process
How to Create Empty Disk Image in Linux
Related posts:
Sreeram Sreenivasan loves coding & writing tech articles. He has helped many Fortune 500 companies in the areas of BI & software development. He has more than 10 years of experience in web development, Python, Linux, SQL and database programming.