开发者

grep match with string1 OR string2

开发者_开发技巧I want to grep 2 patterns in a file on Solaris UNIX.

That is grep 'pattern1 OR pattern2' filename.

The following command does NOT work:

grep 'pattern1\|pattern2' filename

What is wrong with this command?

NOTE: I am on Solaris


What operating system are you on?

It will work with on systems with GNU grep, but on BSD, Solaris, etc., \| is not supported.

Try egrep or grep -E, e.g.

egrep 'pattern1|pattern2'


If you want POSIX functionality (i.e. Linux-like behavior) you can put the POSIX 2-compatible binaries at the beginning of your path:

$ echo $PATH
/usr/xpg4/bin:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:[...]

There is also /usr/xpg6 which is POSIX 1 compatible.

/usr/bin: SVID/XPG3
/usr/xpg4/bin: POSIX.2/POSIX.2a/SUS/SUSv2/XPG4
/usr/xpg6/bin: POSIX.1-2001/SUSv3


That command works fine for me. Please add additional information such as your platform and the exact regular expression and file contents you're using (minimized to the smallest example that still reproduces the issue). (I would add a comment to your post but don't have enough reputation.)


That should be correct. Make sure that you do or don't add the appropriate spaces i.e. "pattern1\|pattern2" vs "pattern1\| pattern2".

Are you sure you aren't just having problems with cases or something? try the -i switch.


That depends entirely on what pattern1 and pattern2 are. If they're just words, it should work, otherwise you'll need:

grep '\(pattern1\)\|\(pattern2\)'


An arcane method using fgrep (ie: fixed strings) that works on Solaris 10...

Provide a pattern-list, with each pattern separated by a NEWLINE, yet quoted so as to be interpreted by the shell as one word:-

fgrep 'pattern1
pattern2' filename

This method also works for grep, fgrep and egrep in /usr/xpg4/bin, although the pipe-delimited ERE in any egrep is sometimes the least fussy.

You can insert arbitrary newlines in a string if your shell allows history-editing, eg: in bash issue C-v C-j in either emacs mode or vi-command mode.


egrep -e "string1|string2" works for me in SunOS 5.9 (Solaris)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜