【问题标题】:Bash Search File for Pattern, Replace Pattern With Code that Includes Git Branch NameBash 搜索文件中的模式,将模式替换为包含 Git 分支名称的代码
【发布时间】:2016-06-15 00:05:33
【问题描述】:

我有一个 README.md 文件,我想用一行代码替换文本标识符 {{CODESHIP_CODE}} — 特别是包含 git 分支名称的构建状态图像代码 sn-p。

我想它会看起来像这样......

  1. 将当前分支 git rev-parse --abbrev-ref HEAD 放入 bash 变量中
  2. 将要搜索的模式/字符串放在变量中。此模式/字符串仅用作标识符,用于快速定位 README.md 文件中我想要输出构建状态图像代码的位置。
  3. 使用sed(可能是grep)在README.md 文件中搜索指定的{{CODESHIP_CODE}} 模式/字符串,并将其替换为构建映像状态代码

我写的代码是这样的:

#!/bin/bash

# Get the current branch
function git_branch {
    git rev-parse --abbrev-ref HEAD
}

# Set variable to current branch
branch=$(git_branch)

# Define the pattern to search for
# This pattern/string gets replaced with the build status image code
id="{{CODESHIP_CODE}}"

# Create build status image code
# Inject the $branch variable into the correct location
codeship_build_status="[ ![Codeship Status for ExampleGitHubUser/ExampleRepo](https://codeship.com/projects/a99d9999-9b9f-9999-99aa-999a9a9a9999/status?branch=$branch)](https://codeship.com/projects/999999)"

# Find the pattern to replace
# Then replace it with the build status image
sed -i -e "s/{{CODESHIP_CODE}}/$codeship_build_status/g" README.md

问题是我不断收到以下错误:

sed: 1: "s/{{CODESHIP_CODE}}/[ ! ...": bad flag in substitute command: 'a'

我不确定如何解决此问题,以便脚本正常工作。任何帮助将不胜感激。

【问题讨论】:

    标签: git bash github sed grep


    【解决方案1】:

    您不能使用包含未转义分隔符的替换字符串。转义字符串中的分隔符,或切换到不同的分隔符。

    ${codeship_build_status////\\/} # escape
    # or
    s%{{CODESHIP_CODE}}%$codeship_build_status%g #
    

    确保新的分隔符不包含在字符串中。

    【讨论】:

    • 这太完美了...根据您的建议,我将代码从 sed -i -e "s/{{CODESHIP_CODE}}/$codeship_build_status/g" README.md 更改为 sed -i -e "s%{{CODESHIP_CODE}}%$codeship_build_status%g" README.md 并按预期工作。感谢您的帮助,非常感谢!
    猜你喜欢
    • 2011-08-16
    • 2012-09-27
    • 2014-11-04
    • 1970-01-01
    • 2018-07-30
    • 2014-08-06
    • 2016-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多