0

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.
  • Add a number after `cut`'s option `-f`, e.g. `1`. – Cyrus May 01 '15 at 18:38
  • First, you're missing an argument to your `cut` command; `-f` takes a number to tell it what field to display. Second, the output of `wc -l` starts with a number of space characters, each one of which is treated as a delimiter by `cut`. You probably want to use `awk` instead. – Mark Reed May 01 '15 at 18:38
  • Oh. I actually had the argument while executing. Probably while pasting here, I missed it somewhere. I will edit the question. I need to use shell script specifically for this purpose. I can't be using awk. – Kumar Divya Rajat May 01 '15 at 18:43

1 Answers1

2

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
William Pursell
  • 204,365
  • 48
  • 270
  • 300