Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use grep to search for multiple strings, but keep order

Tags:

linux

grep

bash

I'm looking for a way to use grep to search for multiple strings but keep the same order. So, for example, if I have this command:

egrep '(string1|string2|string3)' /some/file.txt

I may return:

string2
string1
string3

Depending on the order they are in the file. What I need it to is no matter where in the file the strings are found they always return:

string1
string2
string3

Or if not found found it returns nothing, but the order is still maintained:

string1
string3
like image 277
lostinthewoods Avatar asked Dec 07 '25 19:12

lostinthewoods


1 Answers

If the output can be ordered (i.e. string1 < string2 < string3) you can do the following:

egrep '(string1|string2|string3)' /some/file.txt | sort

If it cannot be ordered, or search for them with three different grep:

egrep 'string1' /some/file.txt
egrep 'string2' /some/file.txt
egrep 'string3' /some/file.txt

or use an array and a for loop:

stringsToSearch=(string1 string2 string3)

for item in ${stringsToSearch[*]}
do
egrep '$item' /some/file.txt
done
like image 134
boh717 Avatar answered Dec 10 '25 12:12

boh717



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!