【问题标题】:How to get only one part of the string without the end in bash如何在bash中只获取字符串的一部分而没有结尾
【发布时间】:2021-12-31 10:22:07
【问题描述】:

我只想获取字符串new-profile-input的一部分,我需要的部分是:没有“-input”的“new-profile”。

我试过这样:

cat automatization_test.sh |  grep -oh "\new-profile-input\w*" | grep -o "\-input\w*"

但是,我得到了输出:

-输入

但是,我需要字符串的第一部分而不是最后一部分。请注意,“new-profile”总是会发生变化,这就是为什么我必须专注于删除“-input”而不是只获取“new-profile”。

提前谢谢你,

【问题讨论】:

  • 试试grep -Poh 'new-profile(?=-input)' automization_test.sh
  • 嗨,丹,感谢您的快速回复,但这不起作用,它确实给了我想要的东西,但我必须指定“新配置文件”,正如我所提到的,这将改变,所以我必须找到另一种方式。如果您有任何其他想法,我如何在没有“-input”的情况下获得“new-profile”,请告诉我。
  • 在 SO 中发布一个可重现的最小示例是一种很好的做法。由于我们不知道文件automatization_test.sh 包含什么内容,因此我们必须猜测您打算做什么。
  • 目前还不清楚你打算用\w*做什么。您的输入是否包含反斜杠或字母 w 的重复?你的意思是重复空白?请查看cat automatization_test.sh | grep -oh "\new-profile-input\w*" 的输出,看看该部分命令是否正确。

标签: string bash grep cat script


【解决方案1】:

使用sed,您可以排除最后一个- 斜杠之后的所有内容,其中-input 将在您的示例字符串中。

$ sed 's/\(.*\)-.*/\1/' automatization_test.sh
new-profile

【讨论】:

    【解决方案2】:

    如果支持,您可以将 -P 用于与 Perl 兼容的正则表达式,匹配整行并使用正向前瞻来断言 - 的最后一次出现在右侧。

    注意,除了使用cat,您还可以在grep 命令的末尾添加文件。

    grep -oP '.+(?=-)' automatization_test.sh
    

    输出

    new-profile
    

    查看regex demo 了解比赛。


    对于更具体的匹配,您可以使用正向前瞻将-input 断言到右侧并匹配非空白字符。

    grep -oP '(?<!\S)\S+(?=-input(?!\S))' automatization_test.sh
    

    查看regex demo 了解比赛。

    【讨论】:

      猜你喜欢
      • 2011-07-02
      • 2012-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-07
      相关资源
      最近更新 更多