Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Hello I am grepping results to file, and then doing cat to show its content on the screen, I want to know how many lines of results I have in my results file and the += it to some counter.

What will be the best way? Any relevant flag to grep or cat?

share|improve this question

migrated from stackoverflow.com Nov 25 '11 at 17:29

This question came from our site for professional and enthusiast programmers.

    
and you can use awk for simple linebased stuff, too ... –  hochl Nov 24 '11 at 15:28

4 Answers 4

up vote 36 down vote accepted

If you have already collected the grep() output in a file, you could output a numbered list with:

cat -n myfile

If you only want the number of lines, simply do:

wc -l myfile

There is absolutely no reason to do:

cat myfile | wc -l

...as this needlessly does I/O (the 'cat') that wc() has to repeat. Besides, you have two processes where one suffices.

If you want to grep() to your terminal and print a count of the matches at the end, you can do:

grep whatever myfile | tee /dev/tty | wc -l
share|improve this answer
6  
Note that wc -l filename will output the filename in addition to the number of lines. If you only want the number, use this form wc -l < filename -- since wc is now reading from stdin, there is no filename to print. –  glenn jackman Nov 24 '11 at 19:31
    
How to save the result of wc -l < filename into a variable to use later? –  Sigur Sep 5 '12 at 23:01
    
@Sigur : LINES=$(wc -l filename); echo ${LINES} –  JRFerguson Sep 6 '12 at 13:00
    
@JRFerguson, thanks. It works. –  Sigur Sep 6 '12 at 21:20
    
@Sigur : I should note that this is POSIX syntax in lieu of the archaic back-ticks often seen; viz. LINES=wc -l filename. Modern shells that are POSIX compliant support the preferred $(...) It's much easier to read, too. –  JRFerguson Sep 6 '12 at 22:06

The -c flag will do the job. For example:

 grep -c ^ filename

will count the lines returned by grep

share|improve this answer

Use

your_command | wc -l

From the manual:

NAME
       wc - print newline, word, and byte counts for each file

...

       -l, --lines
          print the newline counts
share|improve this answer

You can use wc -l to get line count.

Example:

$ cat foobar.txt | wc -l
share|improve this answer
3  
This is the common shell mistake Redundant cat. The effect of this is to create a pipe, executing cat file with its output redirected to the pipe and wc -l with its input redirected from the pipe. But you can eliminate the entire invocation of "cat" by just redirecting wc's input to come from the file rather than the pipe. Just do wc -l foobar.txt. –  Sachin Divekar Nov 25 '11 at 18:44

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.