spartacus
21st March 2003, 11:51
Is it possible to search in Unix for files which contain both of two search patterns?
Spartacus
patvdv
21st March 2003, 11:59
You can use a regular expression in grep:
grep -E "word1|word2" file
The '-E' indicates that you are providing an extended regular expression as search term. The '|' represents 'or'.
Dikkie Dik
21st March 2003, 12:03
Take care that you use the right grep. Especialy on SUN the default is mostly not correct, use /usr/xpg4/bin/grep instead
Hope this helps,
Dick
spartacus
21st March 2003, 12:09
But the output of this contains also files which contains only one of both patterens (sory I think I didn't ask clear enaugh!!).
But I need only Files in which both patterns exist!
Spartaus
(Somtimes it's more difficult to ask the questions, than to give the answer!)
draeger
21st March 2003, 12:21
then try
grep word1 file | grep word2
spartacus
21st March 2003, 12:41
Can you give a little more explanation:
For what stands "file" ?
Spartacus
draeger
21st March 2003, 12:46
ok,
There is two ways of doing this,
grep Artikel * | grep E543
This will show all files in the current directory with Artikel and E543 on the same line.
If you need both patterns to appear anywhere in the file you have to do this
for x in `grep -l Artikel *`
do
grep -l E543 $x
done
grep -l (lower case L) will return only the file name.
Hope this helps
spartacus
21st March 2003, 12:53
Great!!!! that is exact, what I'm looking for!!!
Thanks !!!
Spartacus
FriarTuck
30th May 2003, 17:23
Depening on your needs, you might try:
grep -E "pattern1|pattern2" * | awk -F: '{print $1}' | sort | uniq
One line does it all. One great thing about UNIX is that it will get your answer in so many different ways! :cool: The '-F' passed to awk identifies the field separator (which in this case is the colon). On my HPUX box I had to use 'egrep', so alter accordingly. My linux box works with 'grep -E'. YMMV.
günther
4th June 2003, 16:09
Hm, I'm a bit confused that everybody agrees about that. As fas as I know, the normal grep does not (autmoatically) use regular expressions.
Example: create a file "f" containing lines of 11, 12, 13, 21, 22, 23, 31, 32, 33.
Tests:
1) grep "1|2" f => NOTHING!
2) grep -E "1|2" => all but 33
3) egrep "1|2" => all but 33
Dikkie Dik
4th June 2003, 16:20
Thats the funny part of the "standard" unix commands. The usage of grep and egrep can be different per platform so try
$ man grep
to find out exactly what it is doing for you.
Kind regards,
Dick
patvdv
4th June 2003, 16:41
Always use the '-e' switch for regexp's.