In GitHub actions, when merging a push request to main, I would like to replace the branch name occurrence in a notebook by main
.
For instance, given the below line:
git clone --branch fork1 https://somrepo.git
Using the below regex, all values till the end of the line are replaced, however, my intention is to simply replace fork1
by main
:
sed -i 's/(--branch)(.*)/1 main/'
Another example, given the below line:
"https://colab.research.google.com/github/user/repo/blob/fork2/notebook.ipynb"
Using the below regex, all values till the end of the line are replaced, however, my intention is to simply replace fork2/
by main/
:
sed -i 's/(blob/)(.*)/1 main//'
EDIT:
To clarify my question, my github action use case is to replace the branch name by main
in several files after merging a PR..And no, GITHUB_REF_NAME
would not work in this case since the ref_name would point to the merge branch and not the initial branch where PR was created.
name: Update Branch Name
on:
push:
branches:
- main
jobs:
restore_main_branch_name:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Update .ipynb files
run: |
sed -i "s|${{ github.ref_name }}|main|g" colabLaunchScript.ipynb
- name: Commit changes
run: |
git config --local user.email "[email protected]"
git config --local user.name "GitHub Actions"
git commit -am "Restore main branch name in .ipynb file"
git push -u origin main
2
Answers
First case: match whitespaces, followed by a sequence of non-whitespaces. replace the non-whitespaces with
main
As pointed out by user tripleee,
s
andS
may not be supported by your version of sed. Alternatively you can use:Second case: replace
/fork1/
with/main/
:Note: the chosen subsitution delimiter in this case is
#
instead the usually preferred/
, so that/
does not have to be escaped.To replace the next non-space token after
--branch
, match--branch
followed by one or more spaces, followed by the longest sequence of non-space characters.(If you have
sed -E
this can be simplified tobut this is a non-POSIX extension.)
Your attempt had
.*
which simply matches all characters up until the end of the line (i.e. any character.
repeated as many times as possible*
).To match the next non-space, non-slash token after
/blob/
, match non-space, non-slash characters[^ /]
as many as possible*
; and probably use a different delimiter than slash to simplify things for yourself;If you need the replacement string to come from a shell variable, you need to use double quotes instead of singne ones; this then requires you to use more backslashes in places where the shell will eat some of them. A simple workaround is to use a single-quoted string next to a double-quoted string so you don’t need to add a boatload of backslashes;
The Stack Overflow
regex
tag info page has answers to common beginner questions and links to learning materials.