【问题标题】:Get string after character [duplicate]在字符后获取字符串[重复]
【发布时间】:2013-02-15 10:14:27
【问题描述】:

我有一个如下所示的字符串:

 GenFiltEff=7.092200e-01

使用 bash,我只想获取 = 字符之后的数字。有没有办法做到这一点?

【问题讨论】:

  • 这应该重新打开。 How to grep 询问您如何使用 grep 执行此操作,此问题询问如何在一个字符后获取字符串...不与 grep 绑定。

标签: string bash extract


【解决方案1】:

如果值已经存储在变量中,则使用参数扩展。

$ str="GenFiltEff=7.092200e-01"
$ value=${str#*=}

或使用read

$ IFS="=" read name value <<< "GenFiltEff=7.092200e-01"

不管怎样,

$ echo $value
7.092200e-01

【讨论】:

  • 如果字符串有多个“=”:${str##*=} to get from the last match. ${str#*=} to get from the first match. ${str%%=*} to get until the first match. ${str%=*} to get until the last match.[String Manipulation@tldp.org](tldp.org/LDP/abs/html/string-manipulation.html)
  • 我没有得到第二个解决方案:$ IFS="=" read name value &lt;&lt;&lt; "GenFiltEff=7.092200e-01" using bash 4.4.5
  • 在 4.4.5 中对我来说很好。但是,如果您无法找出问题所在,请打开一个新问题,其中包含您确实得到的结果。
  • 如果这个答案能更详细地解释自己,那就太好了。 #*= 中的每个人到底在做什么?
  • # 运算符从$str 的扩展中省略与模式*= 匹配的最短前缀。
【解决方案2】:

对于第一个= 之后和下一个= 之前的文本

cut -d "=" -f2 <<< "$your_str"

sed -e 's#.*=\(\)#\1#' <<< "$your_str"

对于第一个 = 之后的所有文本,无论是否有多个 =

cut -d "=" -f2- <<< "$your_str"

【讨论】:

  • 适用于简单的情况,但是当字符串中有多个“=”时,这些方法效果不佳。 Chepner 的第一个解决方案简单且更可靠。
【解决方案3】:
echo "GenFiltEff=7.092200e-01" | cut -d "=" -f2 

【讨论】:

  • 请注意,如果分隔符不存在,您可以添加 -s 标志以不显示任何内容
【解决方案4】:
${word:$(expr index "$word" "="):1}

得到7。假设您的意思是整个字符串的其余部分,请忽略 :1

【讨论】:

  • $value = ${word:$(expr index "$word" "=")} 对我来说很好,可以在等号后返回所有内容。
【解决方案5】:

这应该可行:

your_str='GenFiltEff=7.092200e-01'
echo $your_str | cut -d "=" -f2

【讨论】:

    猜你喜欢
    • 2015-02-23
    • 2016-02-28
    • 2011-12-20
    • 2014-05-04
    • 2017-09-06
    • 2013-08-12
    • 1970-01-01
    • 2013-08-12
    相关资源
    最近更新 更多