Quantcast
Channel: How to use grep to get the matching part only, without introducing extra newlines - Unix & Linux Stack Exchange
Viewing all articles
Browse latest Browse all 2

How to use grep to get the matching part only, without introducing extra newlines

$
0
0

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.

Example:

input(output of my command):

banana apple bananaapple bananas banned

regex:

ban[a-z]*

output by grep -o:

bananabananabananasbanned

expected output:

bananabananabananasbanned

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.


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images