0

This question already has an answer here:

Suppose I have used the grep command :

grep 'pattern' 'filename'

and have got the result :

John
Brown

Is there any way to concatenate the outputs into a single one like:

John Brown

And also is there any way to count the number of outputs and store it in a separate variable?

marked as duplicate by don_crissti, Costas, dhag, jimmij, Archemar Sep 14 '15 at 20:20

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    Don't be afraid to use the search bar (or click on the links under "Questions that may already have your answer" while entering your question) to see if similar questions have an answer that you can use. – Jeff Schaller Sep 14 '15 at 19:09
2

One way -- using $() command substitution:

echo $(grep 'pattern' 'filename')

Edited after the addition of the count requirement: Since you presumably have a filename, just run grep again with the --count option:

count=$(grep --count 'pattern' 'filename')
  • It just occurred to me that there's an outside chance you're using a grep that does not have the -c (--count) option, in which case a common way to count matches is to use "wc -l", eg: count=$(grep 'pattern' 'filename' | wc -l) – Jeff Schaller Sep 14 '15 at 19:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.