bookishq
bookishq

Reputation: 193

grep command to extract a word

Here is my file.

    this is temp1
    this is temp2
    this is temp3

How to use grep command that while looking for pattern 'temp', the result should be displayes as only 'temp1, temp2, temp3', instead of whole sentences.

Thanks

Upvotes: 3

Views: 14740

Answers (3)

souter
souter

Reputation: 386

You can break the line multiple lines then feed that into grep e.g.

grep myword | tr ' ' '\n' | grep myword

Upvotes: 1

andyc
andyc

Reputation: 177

You would probably want to use grep in combination with sed. sed uses perl-style regular expressions and gives you much more pattern matching power (well, in my opinion). This will get get exactly what you need:

grep temp yourFileName | sed -e "s/.*(temp[0-9]*).*/\1/"

But if you want more than just temp[number], you can match "temp" then continue matching until you hit a whitespace. This will do the trick:

grep temp yourFileName | sed -e "s/.*(temp[^ ]*).*/\1/"

You may also need to escape the brackets if this is on the command line:

grep temp yourFileName | sed -e "s/.*\(temp[^ ]*\).*/\1/"

Upvotes: 3

ymonad
ymonad

Reputation: 12090

you can use -o option

$ grep -o "temp[0-9]"

Upvotes: 13

Related Questions