3

I faced an interesting question to count the words from a file where the number of lines were also specified as a command line argument. For example if the input text file had -

Unix is an OS
Linux is the child of Unix
Unix is fun.
End of File

The command to be executed is:

bash test.sh unix.txt 3

where unix.txt is the test file containing the sentences and 3 is the number of lines whose words are to be counted. The answer would be 13.

I have used the basic wc commands but none of them would give the correct answer.

So, I tried to use a for loop, but I could not specify how to take only those number of lines.

0

4 Answers 4

10

With head -n 3 unix.txt you get the first three lines of your file and then you can pipe them to wc

So for any arbitrary filename stored in the $file shell variable:

{ head -n 3 | wc -w; } < "$file"

Or:

head -n 3 -- "$file" | wc -w

Though the latter wouldn't work with a file called - with some head implementations, and output 0 in addition to an error message (by head) when the file can't be opened, and the failure exit status in that case would be lost unless you use the (non-standard) pipefail option found in some shells.

2
  • Should it be like this - head -n $2 $file | wc -w where the specified number is the second command line argument and file is the variable with the name of the text file ?
    – Chris
    Mar 2, 2020 at 8:08
  • Yes, I want it be print all the words upto the 3rd line if 3 is specified.
    – Chris
    Mar 2, 2020 at 9:34
4

Try also

awk -v"LNR=$2" 'NR > LNR {print SUM; exit} {SUM+=NF}' file
13
2

We can do it by awk

awk '{print NF}' unix.txt

Word count along with lines

awk '{print NF" "$0}' unix.txt

Word count with line numbers

awk '$0="line"NR": "NF'  unix.txt
awk '$0="line"NR": "NF'  unix.txt | grep line3
1

Your script takes two arguments ,

So , in the script , you can use it like below :

sed -n "/\w/{1,$2 p;}"  $1 | wc -w

where $1 contains your file name $2 contains your total number of lines need to search

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .