I have a output from a command that I want to pipe to some kind of grep command to obtain the part in each line that matches a given regex, and only output the matching part, without introducing newlines

I know grep -o can do something quite similar but it generates a newline for each match, and the output of my command also contains many new lines.


input(output of my command):

banana apple banana
apple bananas banned



output by grep -o:


expected output:


One thing I can come up with is to use tr to replace newline character to some character that is unlikely to appear in the output of the command, feed the output to grep -o, and then use tr to get back the newline.

mycommand|tr '\n' @|grep -o regex|tr -d '\n'|tr @ '\n'

However I suppose there should be some better solutions. Any help would be appreciated.

  • Are you open to solutions using other tools - such as perl? Dec 7, 2017 at 2:51
  • @steeldriver Yes, I am open to options using other tools though personally I prefer GNU tools. I am not sure about the efficiency but can I assume that perl performs as good as GNU grep, sed, etc.? Dec 7, 2017 at 3:19

1 Answer 1


If you don't mind using perl:

mycommand | perl -lne 'print join "", /ban[a-z]*/g'

The matches on each line are returned in a list context, which you can join with an empty delimiter.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .