只打印匹配的字,而不是整行通过grep [英] Print only matching word, not entire line through grep

查看:489
本文介绍了只打印匹配的字,而不是整行通过grep的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对bash中的shell编程很熟悉,但由于某些原因 egrep -o 仅打印匹配的字符不起作用,并显示如下错误。



环境是ksh unix控制台上的putty,而不是linux或ubuntu终端......任何建议值得赞赏!



终端输入&输出:

  AB12 $ echo我是男孩| grep -wam
我是男孩
AB12 $回声我是男孩 egrep -oam
egrep:非法选项-o
用法:egrep [-bchilnsv] [-e exp] [-f文件] [字符串] [文件] ...
AB12 $ echo $
ksh:echo $:找不到
AB12 $ echo $ SHELL
/ bin / ksh
AB12 $ echo我是男孩 grep -oam
grep:非法选项 - o
用法:grep -hblcnsviw模式文件。 。 。
AB12 $

PS: grep只能显示与搜索模式相匹配的文字吗?

解决方案

我假设这是您连接到的Solaris机器。 Solaris的版本 grep 没有 -o 选项。所以你可以在你的Solaris机器上安装GNU grep(它可能已经安装在 / usr / sfw / bin ,或者你也可以运用 pkg install // solaris / text / gnu-grep );或

  • 改为使用awk(请参阅此SO问题



  • 查看我的信箱:

      $ uname 
    SunOS
    $ echo我是男孩| grep -oam
    grep:非法选项 - o
    用法:grep -hblcnsviw模式文件。 。 。
    $ echo我是男孩| / usr / sfw / bin / ggrep -oam
    am


    I am familiar with shell programming in bash, but for some reason egrep -o to print only matching words is not working and displays error as below.

    Environment is ksh unix console on putty and not linux or ubuntu terminal......any advice is appreciated!

    Terminal input & output :

    AB12 $ echo "i am a boy" | grep -w "am"
    i am a boy
    AB12 $ echo "i am a boy" | egrep -o "am"
    egrep: illegal option -- o
    usage: egrep [ -bchilnsv ] [ -e exp ] [ -f file ] [ strings ] [ file ] ...
    AB12 $ echo$
    ksh: echo$: not found
    AB12 $ echo $SHELL
    /bin/ksh
    AB12 $ echo "i am a boy" | grep -o "am"
    grep: illegal option -- o
    Usage: grep -hblcnsviw pattern file . . .
    AB12 $
    

    PS : Similar thread but tried already : Can grep show only words that match search pattern?

    解决方案

    I am assuming this is a Solaris box you are connecting to. Solaris' version of grep does not have the -o option. So you can either

    • install the GNU grep on your Solaris box (it might already be installed in /usr/sfw/bin, or you might have luck with pkg install //solaris/text/gnu-grep); or
    • use awk instead (see this SO question)

    See on my box:

    $ uname
    SunOS
    $  echo "i am a boy" | grep -o "am"
    grep: illegal option -- o
    Usage: grep -hblcnsviw pattern file . . .
    $  echo "i am a boy" | /usr/sfw/bin/ggrep -o "am"
    am
    

    这篇关于只打印匹配的字,而不是整行通过grep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆