【问题标题】:Bash - get String between two charactersBash - 获取两个字符之间的字符串
【发布时间】:2021-03-25 13:23:25
【问题描述】:

如何获取两个特定字符之间的字符串,仅在 bash 中 [不使用 grep 或 sed]

例如

input=hostname~web:sit

我想从上面的输入中提取web

${hostname#*~} 给我的输出为web:sit,但我只需要输出中的web

从另一个帖子我可以看到

% strips from end of $var, 最多模式。但不知道如何应用。

请帮忙

【问题讨论】:

  • 试试sed -E 's/.*~([^:]+):.*/\1/' <<< "$input"
  • awk -F '[~:]' '{print $2}' <<< "$input"
  • @0stone0:这似乎不太正确,因为那是 grep 的具体问题,而 OP 想在 bash 本身中执行此操作。
  • 在您的答案下方有一个仅限 bash 的解决方案。不使用 extglob,但问题还是一样?
  • No questions cannot be same as other question is specific ask using grep

标签: linux bash


【解决方案1】:

bash 中使用extglob,您可以一步完成

shopt -s extglob
input='hostname~web:sit'
echo "${input//@(*~|:*)/}"

web

这里@(*~|:*) 匹配从开始到~ 字符的子字符串或从: 到结束的子字符串。使用//,我们将所有此类实例替换为空字符串。


还有一个sed 解决方案:

sed -E 's/.*~([^:]+):.*/\1/' <<< "$input"

web

【讨论】:

  • 感谢您的回答,当我尝试命令时,回显正在打印输入而不是 web -bash-4.2$ input='hostname~web:sit' -bash-4.2$ echo "${input//@(~|:)/}" 主机名~web:sit
  • 对不起,我错过了复制 shopt 行的答案。请立即尝试更新的答案。
【解决方案2】:

分两步完成:

input=hostname~web:sit

rightpart=${input#*~}   # remove prefix up to "~" (included)
output=${rightpart%:*}  # remove suffix from ":" (included)

echo $output

【讨论】:

    【解决方案3】:

    另一种选择,使用cut,可以从GNU Core Utilities 获得:

    1. 让所有人落后 ~
    2. 获取所有之前 :
    input='hostname~web:sit'
    echo "$input" | cut -d '~' -f2 | cut -d ':' -f1
    # web
    

    Try it online!

    【讨论】:

      猜你喜欢
      • 2020-10-15
      • 2012-07-07
      • 1970-01-01
      • 2022-11-02
      • 2012-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多