【问题标题】:Stripped first X characters from string in shellscript using SED and now store as variable?使用 SED 从 shell 脚本中的字符串中删除第一个 X 字符,现在存储为变量?
【发布时间】:2013-07-20 06:51:22
【问题描述】:

我知道这与问题How can I strip first X characters from string using sed?非常相似

但我无法将输出字符串作为变量存储在我的 bash 脚本中

myString='Foo: 1234'
echo "$myString"| sed -r 's/^.{5}//'

产生所需的结果但它没有存储在变量中......当我尝试时:

myVariable1=$('"$myString"| sed -r 's/^.{5}//'')
myVariable2='"$myString"| sed -r 's/^.{5}//''
myVariable3=$(""$myString"| sed -r 's/^.{5}//'")
myVariable4=""$myString"| sed -r 's/^.{5}//'"

有人愿意告诉我哪里出错了

【问题讨论】:

    标签: regex linux bash sed


    【解决方案1】:

    您不需要 sed。 bash 可以做到。

    $ myString='Foo: 1234'
    $ myVar=${myString:5}
    $ echo $myVar
    1234
    

    【讨论】:

    • 是的,我可以确认这适用于您展示的示例,谢谢,但是当我尝试使用我的实际字符串时,它没有!我需要注意这种特殊字符吗?我的字符串是:'block.GetHash = 21f909a7d7efb8c7b0f6bee1f518bf1bbb7651b999b8e7cd6a2edc8f785b65a5'
    • $测试= 'block.GetHash = 21f909a7d7efb8c7b0f6bee1f518bf1bbb7651b999b8e7cd6a2edc8f785b65a5' ---- $回波$ {试验:5} .GetHash = 21f909a7d7efb8c7b0f6bee1f518bf1bbb7651b999b8e7cd6a2edc8f785b65a5 跨度>
    【解决方案2】:

    你可以保留echo:

    myVar=$(echo "$myString"| sed -r 's/^.{5}//')
    

    或使用此处的字符串:

    myVar=$(sed -r 's/^.{5}//' <<<"$myString")
    

    【讨论】:

    • 太棒了,我不知道你可以通过回声,问题解决了:) 谢谢
    猜你喜欢
    • 2021-01-20
    • 1970-01-01
    • 2012-07-13
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    • 2017-06-18
    相关资源
    最近更新 更多