Say I have a file with the following text:

Hello there,
How are you?

How can I grep for Hello and are such that the output of grep looks like:

  • So you only want the words passed to grep to be included in the comma-separated output if they are in the contents of the file? – drs Oct 20 '14 at 18:38
  • That is correct – user88557 Oct 20 '14 at 18:42
  • 1
    You can't do it just with grep. You can pipe the output of grep to another command that combines the lines with commas between them. – Barmar Oct 20 '14 at 18:42

You can try the following:

grep -Eo "Hello|are" file | sed '$!N;s/\n/,/'
grep -o "Hello\|are" test | tr '\n' ','

-o to only output matching strings, then replace \n with ,.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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