grep使用标准正则表达式有什么注意事项?

history|grep ssh是正常的,可以找到字符串里面带ssh的命令,
但是history|grep '^ssh'不对,history|grep -e '^ssh'history|grep -i '^ssh'都不对。。而且还是不正常退出的。
到底grep里的正则表达式有什么不一样的呢?
网上搜的时候好像直接用history|grep '^ssh'就可以了,不明白我这是个什么情况。。。
ubuntu和Mac上都试过了。。

➜ zhutou@localhost:~  >grep --version
grep (BSD grep) 2.5.1-FreeBSD
阅读 6.7k
2 个回答

好吧可以关闭了的样子。。。
history前面有一排序号,序号可以用!n(n代表任意数字)在shell中召唤出来那条命令。。。
因此实际上不存在ssh开头的命令。。。

首先我使用的grep版本

grep --version
GNU grep 2.6.3

Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

不过应该和题主的区别不大。
简单看下grephelp帮助文档,

[honwhy@localhost ~]$ grep --help
Usage: grep [OPTION]... PATTERN [FILE]...
Search for PATTERN in each FILE or standard input.
PATTERN is, by default, a basic regular expression (BRE).
Example: grep -i 'hello world' menu.h main.c

Regexp selection and interpretation:
  -E, --extended-regexp     PATTERN is an extended regular expression (ERE)
  -F, --fixed-strings       PATTERN is a set of newline-separated fixed strings
  -G, --basic-regexp        PATTERN is a basic regular expression (BRE)
  -P, --perl-regexp         PATTERN is a Perl regular expression
  -e, --regexp=PATTERN      use PATTERN for matching

由于历史原因grep刚开始支持的正则表达式比较有限,你会看到-E这个选择,如果使用grep -E就能够使用扩展的正则表达式了,grep -E也相当于egrep;要使用grep -e这种形式,正确的方式grep -e='*[0-9]\{1,\} ssh'实在抱歉,在普通正则表达式模式下,不知道怎么匹配空白。

1.history|grep '^ssh'这个不对是因为history输出每行有空白字符+数字+空白字符,然后才是历史命令,^ssh没有匹配到ssh开头的记录。
2.history|grep -e '^ssh'语法问题
3.history|grep -i '^ssh'加了-i参数,只是表示匹配过程中忽略大小写。

要找历史记录中以ssh开头(而且不能是ssh-keygen这种形式的,这个是我加的假设),推荐一下做法
1.使用扩展的正则表达式
egrep '^\s+[0-9]+\s+ssh\>($| )'我表示以后再也不给自己挖坑了,
有哪位大神告诉我为什么egrep '^\s+[0-9]+\s+\>ssh\>'为什么不行,为什么还要匹配ssh-keygen的情况。
2.将前面的行数去掉
history | cut -c 8-,只不过你或许要考虑history | cut -c 8- | grep ^ssh也会匹配到ssh-keygen的情况。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题