模式的 Bash 搜索文件,用包含 Git 分支名称的代码替换模式 [英] Bash Search File for Pattern, Replace Pattern With Code that Includes Git Branch Name
问题描述
我有一个 README.md 文件,我想用一行代码替换文本标识符 {{CODESHIP_CODE}}
- 特别是包含 git 分支的构建状态图像代码片段名字.
I have a README.md file where I'd like to replace a text identifier {{CODESHIP_CODE}}
with a line of code – specifically a build status image code snippet that includes the git branch name.
我认为它看起来像这样......
I'm thinking it would look something like this...
- 将当前分支
git rev-parse --abbrev-ref HEAD
放在bash变量中 - 将要搜索的模式/字符串放在变量中.此模式/字符串仅用作标识符以快速定位我想在 README.md 文件中输出构建状态图像代码的位置.
- 使用
sed
(可能是grep
)在 README.md 文件中搜索指定的{{CODESHIP_CODE}}
模式/字符串并替换它带有构建图像状态代码
- Place the current branch
git rev-parse --abbrev-ref HEAD
in bash variable - Place the pattern/string to search for in a variable. This pattern/string is just used as an identifier to quickly locate where in the README.md file I want to output my build status image code.
- Use
sed
(possiblygrep
) to search the README.md file for the specified{{CODESHIP_CODE}}
pattern/string and replace it with the build image status 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
问题是我不断收到以下错误:
The problem is that I keep getting the following error:
sed: 1: "s/{{CODESHIP_CODE}}/[ ! ...": 替换命令中的错误标志:'a'
我不确定如何解决此问题,以便脚本正常工作.任何帮助将不胜感激.
I'm not sure how to resolve this issue, so that the script works correctly. Any help would be greatly appreciated.
推荐答案
您不能使用包含未转义分隔符的替换字符串.转义字符串中的分隔符,或切换到不同的分隔符.
You can't use a replacement string that contains the unescaped delimiter. Escape the delimiters in the string, or switch to different ones.
${codeship_build_status////\/} # escape
# or
s%{{CODESHIP_CODE}}%$codeship_build_status%g #
确保新的分隔符不包含在字符串中.
Make sure the new delimiter isn't contained in the string.
这篇关于模式的 Bash 搜索文件,用包含 Git 分支名称的代码替换模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!