【问题标题】:Get part of a string in bash在bash中获取字符串的一部分
【发布时间】:2011-07-02 15:18:24
【问题描述】:

我有一些日志文件,我用 grep 查找特定的字符串:

grep UncategorizedLdap *

我得到了大约 33 个结果:

2009-01-01:org.springframework.ldap.UncategorizedLdapException: Uncategorized exception occured during LDAP processing; nested exception is javax.naming.NamingException: [LDAP: error code 1 - Operations Error]; remaining name 'ou=ABC'
2009-01-02:org.springframework.ldap.UncategorizedLdapException: Uncategorized exception occured during LDAP processing; nested exception is javax.naming.NamingException: [LDAP: error code 1 - Operations Error]; remaining name 'ou='
2009-01-02:org.springframework.ldap.UncategorizedLdapException: Uncategorized exception occured during LDAP processing; nested exception is javax.naming.NamingException: [LDAP: error code 1 - Operations Error]; remaining name 'ou=ABD'
2009-01-03:org.springframework.ldap.UncategorizedLdapException: Uncategorized exception occured during LDAP processing; nested exception is javax.naming.NamingException: [LDAP: error code 1 - Operations Error]; remaining name 'ou=ABE'
...

如何修改 grep 调用以仅返回

ou=ABC
ou=
ou=ABD
ou=ABE
...

?

【问题讨论】:

    标签: bash grep substring


    【解决方案1】:

    您可以将输出通过管道传输到 perl:

    grep UncategorizedLdap * | perl -lpe '($_) = /(ou=\w*)/'
    

    如果您没有安装 Perl,这里有一个 bash-only 解决方案:

    grep UncategorizedLdap * |
    while read line; do
        line=${line#*\'}
        line=${line%\'*}
        echo $line
    done
    

    【讨论】:

    • 我已经为 cygwin 安装了 perl,但它不能正常工作 - 它会打印整行。
    • @hsz:我猜问题出在双引号中。我发布了另一个 Perl 单行代码
    【解决方案2】:

    如果你有 GNU grep(在 Cygwin 中应该是这种情况):

    grep -Po "UncategorizedLdap.*'\Kou.*?(?=')" *
    

    将选择行并在一个命令中挑选出字符串。它使用支持环视的 Perl 兼容正则表达式。 \K 之前的部分是一个lookbehind,用于进行匹配,但不包含在输出中。 (?=) 中的字符串在这种情况下是单引号,它是前瞻,它也不包含在输出中。 -o 选项仅打印行的匹配部分(不从输出中排除)。

    【讨论】:

      【解决方案3】:

      如果你使用的是 bash,那么有时你可以只使用 bash

      for file in *
        while read -r line
        do
           case "$line" in
             *UncategorizedLdap* )
                line=${line#*\'}
                line=${line%\'*}
                echo $line ;;
           esac
        done < $file
      done
      

      【讨论】:

        猜你喜欢
        • 2012-09-27
        • 2015-02-02
        • 2016-06-13
        • 2012-08-26
        • 1970-01-01
        • 2014-12-20
        相关资源
        最近更新 更多