Kumar Divya Rajat
Kumar Divya Rajat

Reputation: 187

How to format output for number of lines, words, characters for a file in bash?

I am trying to write a shell script which will count the number of lines, words and characters in Bash.

    echo "Enter file name"
    read file
    if [ -f $file ]
    then
        echo "The number of lines in $file are "
        echo $(wc -l $file | cut -d " " -f1 )
    fi

The program does take the output but the cut part is not formatting the output. I checked the syntax for cut as well as wc. How do I get the number of lines without the filename at the end which is the default characteristic of the wc command?

This is the output I am getting now.

    Enter file name
    pow.sh
    The number of lines in pow.sh are

This is what is required.

    Enter file name
    pow.sh
    The number of lines in pow.sh are 3.

Upvotes: 0

Views: 813

Answers (1)

William Pursell
William Pursell

Reputation: 212198

The typical way omit the filename is to avoid giving it to wc in the first place:

wc -l < $file

So you end up with:

printf "The number of lines in $file is "
wc -l < $file

Upvotes: 2

Related Questions