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.
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."
bash? Did you out extra spaces in my command maybe?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
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.