Padawan
Padawan

Reputation: 313

Grep for a string in a specific order

I need to grep a large file for words (really a string of characters) in a specified order. I also need the string to be able to contain a colon ":". For example, if the words are "apple", "banana", and ":peach", I will get the line that says, "apple cherries banana cool :peach" but not "apple :peach cherries banana cool". I would really like to be able to have one string and not grep commands in other grep commands. I am not concerned about searching whole words only.

Upvotes: 1

Views: 2248

Answers (1)

zzevannn
zzevannn

Reputation: 3714

grep "apple.*banana.*:peach" file

e.g.

$ echo "apple cherries banana cool :peach" | grep "apple.*banana.*:peach"
apple cherries banana cool :peach
$ echo "apple :peach cherries banana cool" |grep "apple.*banana.*:peach"
$

Pretty simple regex. the "apple", "banana" and ":peach" portions are just literal strings. The .* in between them is are two regex operators - the . will match any character, and the * says that the previous match can match 0 or more times.

In essence we're saying find these literal strings in this order, with any number of characters between them (including none, so even "applebanana:peach" would match.)

Upvotes: 1

Related Questions