Number of records in a file

hi gurus

i'm trying to get the count of number of records of a file

as : wc -l file1.txt

iam getting the correct count by in out put i'm getting the file name too

i get the output as follows "7 file1.txt"

my question is how to avoid filename in the output.

might be a basic question but iam newbie to unix.

appreciate any kind of help.

thanks

You can "cut" out the number of records or you can use awk to count records:

awk '{n++} END {print n}' file1.txt

or, depending on your shell, you can strip off the filename:

#! /usr/bin/ksh

x="7 file1.txt"  # your command would be x=$(wc -l file1.txt)
print ${x% *}

hi

It was very helpful, working fine

thanks

Just curious how this command works

does it count each and every records and store it in variable 'n'

can you please eloborate some details.

thanks

sish

 wc -l < filename 

gives the result without the filename, because wc is reading from stdin.

{n++} - for every line read from input, add one to n. The first time n is encountered it is assumed to be zero.
END{} runs after all of the lines in the file have been read.

Thanks jim

FYI. If you happen to have a file with out an EOL (newline) as the last line of the file, it is not included as part of the count. The awk command will include the last line regardless of terminator.

Yup.

And to find the number of lines in a file requires reading the entire file.
So pick the tool and code you think applies. In UNIX there are usually several ways to do one thing.

simple way would be "cat file1.txt | wc -l "

thanks a lot for all the information and quick replies

:slight_smile:

.... and why exactly do you need a 'cat'?

What do you mean?

he means that,

when wc itself can get u the count,
why do u want to use cat and pipe to wc explicitly,
there isnt any need for that!!!

Because it would prevent the file name from appearing in the output, which is what the original poster wanted.

$ wc -l file.txt
$ 42 file.txt
$ cat file.txt | wc -l
$ 42

pls read the previous post by jim.

how about this....

$ wc -l < file.txt
42

Yep, that works as well.

take a look at UUOC

I'm well aware of the "useless use of cat". I am not arguing that chittari's solution is the best (in fact, I find it evil; I would use jim's solution), but it could be an acceptable solution for some people. In this thread, jim also said, "So pick the tool and code you think applies. In UNIX there are usually several ways to do one thing."

Lets add one more.....

wc -l filename|awk '{print $1}'

Here's one that will hurt vgersh99 :stuck_out_tongue:

cat file.txt | wc -l | cut -d " " -f $(wc -l file.txt | wc -w)