Sunday, 20 November 2016

Script to report number of characters, words & lines in a file

While browsing through a shell scripting forum I came across a problem statement stating that someone wanted to write a script to report number of characters, words & lines in a file without using the wc command which would have been well very straight forward. 

So I decided to give it a try & after a while to some hits & misses I got a working script ready. 
Here is the script:

[root@cclient1 ~]# cat filecheck.sh
#!/bin/bash

case $2 in

-h) echo -e "The number of letters in file are: \n"

        b=0
        for i in `cat $1 | tr -d " "`
        do
        a=$(expr length $i)
        let b+=$a
        done
        echo $b
        ;;

-k) echo -e "The number of words in the file are: \n"

    awk  '{total=total+NF}; END {print total  }' $1
        ;;

-s) echo -e "The number of lines in file are: \n"
    awk  ' END {print NR }' $1
        ;;

*) echo "Incorrect usage"
    ;;

esac


Below is a description of what's happening.
  • In the first part, the for loop iterates through each line of the file. I used tr to remove spaces so that the entire line is treated as a single string. Then I used expr built in to calculate the length of the string & finally used let to add the values for string lengths of the individual lines.
  • In the second part, I used the number of fields built in variable in awk to sum up the number of fields in each line & print the final result.
  • In the final part, I used the number of records built in from awk to display the number of lines in the file.

Here's a demo of the script in action:

[root@cclient1 ~]# cat test
sa hi l su ri
un ix li n ux
hp ux


[root@cclient1 ~]# ./filecheck.sh test -h
The number of letters in file are:

22
[root@cclient1 ~]# ./filecheck.sh test -k
The number of words in the file are:

12

[root@cclient1 ~]# ./filecheck.sh test -s
The number of lines in file are:

3

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...