0

I've tried as below

grep 'test' testdoc|wc -l 

I am getting the count of matched string. but I need to get the count and print the matched Lines. Can any one help me out.

0

3 Answers 3

1

Like this:

grep pattern file | tee >(wc -l)

tee prints all the lines grep found and then passes them also to a process that counts the lines. It's like a T joint in plumbing, where the water comes in one side and goes out two others - i.e. a splitter.

Note that this is called "process substitution" and is a bash-specific construct and there is no space between > and (.


You can also do it with awk like this:

awk '/pattern/{print;n++} END{print n+0}' file

That says... "If the line matches pattern, print it and increment n. At the end, print n - after adding zero to ensure it is a number not an empty string if there were no matches."

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks mark. But getting the following error. "Missing name for redirect"
Are you using bash? Did you out extra spaces in my command maybe?
1
grep 'test' testdoc|wc -l 

counts the number of lines where your pattern occurs and it is equivalent to

grep -c 'test' testdoc

To take into account multiple matches per line, use the option -o

grep  -o 'test' testdoc|wc -l

To get both lines and count you could use tee outputting to a temporary file f and append to f the result of the second grep:

grep "test" testdoc |tee >(wc -l 1>&f)|grep -o "test"|wc -l 1>>f && cat f

# or to get both outputs in a line:
grep "test" testdoc |tee >(wc -l|tr '\n' ' ' 1>&f)|grep -o "test"|wc -l 1>>f && cat f

Here's another solution not using grep (since in some distributions the -o option is missing)

awk 'BEGIN{lCount=0;count=0}{c=gsub(/test/,"");count+=c;if(c)lCount+=1;}END{print(lCount,count)}' testdoc 

Comments

1

with awk:

grep 'test' testdoc|awk 'END{print NR}1'

In awk, 1 always evaluates to true, it performs default operation {print $0} - prints the current line stored in $0

NR is the number of the current record/line and in END block (or on the last line of the file) is it the number of lines in the file.

END block executes after executing all the awk code. so this is the last awk code going to execute.

2 Comments

You're welcome. If it helped, you can accept (and upvote) my answer. ^_^
@tso : Could you please explain the part awk 'END{print NR}1' ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.