Search Multiple strings and print them in the order of search strings
One of my colleagues asked this query to me. And I liked the query very much.So I started thinking about that.
For example i have a below file:
1 name1
2 name2
3 name3
4 name1
5 name4
6 name2
7 name1
Now i want to find strings in the file , lets say in the order name1, name2, name3, name4.2 name2
3 name3
4 name1
5 name4
6 name2
7 name1
And i also want the output to be in the same order in the way i searched as below:
1 name1
4 name1
7 name1
2 name2
6 name2
3 name3
5 name4
Obviously we cannot do this with a single grep command without any temporary files being created.4 name1
7 name1
2 name2
6 name2
3 name3
5 name4
So I thought perl would be a better option for this. So I came up with a simple perl solution.
perl -lne '/name1/?push @a,$_:
(/name2/?push @b,$_:
(/name3/?push @c,$_:
/name4/?push @d,$_:next));
END{print join "\n",@a,@b,@c,@d}' your_file
(/name2/?push @b,$_:
(/name3/?push @c,$_:
/name4/?push @d,$_:next));
END{print join "\n",@a,@b,@c,@d}' your_file
And this worked like a a charm.
0 comments: