lostinthewoods
lostinthewoods

Reputation: 55

Use grep to search for multiple strings, but keep order

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

Upvotes: 3

Views: 5689

Answers (3)

tripleee
tripleee

Reputation: 189447

Scan once, then print matches for each expression in turn. If an input matches multiple expressions, it is listed in the first set that matched.

I'm using colon as expression delimiter; obviously, feel free to change as you see fit.

awk -v 'expr=string1:string2:string3' '
    BEGIN { n=split(expr, e, /:/);
      for(i=i; i<=n; ++i) m[i]="" }
    { for(i=1; i<=n; ++i) if ($0 ~ e[i]) {
      m[i]=m[i] $0 ORS; next } }
    END { for (i=1; i<=n; ++i) printf m[i] }' file

Upvotes: 2

Alberto Coletta
Alberto Coletta

Reputation: 1603

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

Upvotes: 3

Hack Saw
Hack Saw

Reputation: 2781

How to automate doing it one at a time:

echo "string1 string2 string3" | xargs -n 1 -J % egrep % /some/file.txt

Upvotes: 0

Related Questions