grep display word only

Folks, is it possible to display only words with grep (or any built-in ultility)?

I have more than 1 pattern to search, say apple & orange

The text goes like this:

So I need to display all the words starting with apple or orange

The output should be:

Any idea?

You can use awk

awk '{for(i=1;i++<=NF;)if($i~/^apple|^orange/) print $i}' file

..and please read the forum rules.

With grep:

tr ' ' '\n' < file | grep -E "^apple|^orange"

or egrep:

tr ' ' '\n' < file |egrep "^apple|^orange"

You are legend! :slight_smile:

danmero: Thanks, but i should start at 0, and if any word start with a or o, it will also appear in the output, too.

Yep, I correct the line

# time awk '{for(i=1;i<=NF;i++)if($i~/^apple|^orange/) print $i}' file > newfile1

real    0m0.715s
user    0m0.550s
sys     0m0.128s
# time tr ' ' '\n' < file | grep -E "^apple|^orange" > newfile2

real    0m0.864s
user    0m0.550s
sys     0m0.238s
# diff newfile1 newfile2
#

If you have GNU grep:

grep -oE '\b(apple|orange)\S*'

Otherwise with Perl:

perl -nle'print join"\n",/\b((?:apple|orange)\S*)/g'
undef $/;
open FH,"<filename";
$str=<FH>;
$str=~s/\n/ /g;
close FH;
print "$_\n" foreach(grep {m/apple|orange/;} (split(" ",$str)));

Thank guys, I learn smt new :slight_smile: