【问题标题】:How to get the string between two dots in bash?如何在bash中获取两个点之间的字符串?
【发布时间】:2015-11-13 16:38:51
【问题描述】:

我有几个这种格式的 git-Repos:

product.module1.git
product.module2.git
...

现在我只想遍历列表以获取只是

module1
module2

我怎样才能做到这一点?我已经尝试将 ls 与 grep 结合使用,但我无法删除第一个和最后一个字符串部分。

【问题讨论】:

  • 您不必写“谢谢”或“问候”,或者用您的名字签名,因为它会自动显示在您帖子的右下角。

标签: git bash substring


【解决方案1】:

cut 将完成这项工作:

cut -d . -f2 file
module1
module2

或 awk:

awk -F. '{print $2}' file
module1
module2

【讨论】:

    【解决方案2】:

    如果您的 grep 支持 -P 选项:

    $ grep -oP '(?<=[.])\w+(?=[.])' file
    module1
    module2
    

    (?&lt;=[.]) 是在后面看。在这种情况下,它会在一段时间后匹配。

    \w+ 匹配任意数量的单词字符。

    (?=[.]) 是一个展望。在这种情况下,它恰好在句点之前匹配。

    【讨论】:

    • 非常有用而且非常快。谢谢。
    【解决方案3】:
    while read -r line; do 
      if [[ "$line" =~ \.(.*)\. ]]; then
        echo "${BASH_REMATCH[1]}"
      fi
    done < file
    

    输出:

    模块1 模块2

    【讨论】:

      【解决方案4】:

      在 Bash 中,使用数组和 IFS 进行标记很容易:

      var="product.module1.git"
      IFS="." tokens=( ${var} )
      echo ${tokens[1]}
      # this outputs module1
      

      【讨论】:

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