Extracting part of a string on jenkins pipeline

ぃ、小莉子 提交于 2019-12-01 03:09:02

问题


I am having some trouble with the syntax in my pipeline script.

I am trying to capture everything after the last forward slash "/" and before the last period "." in this string git@github.com:project/access-server-pd.git (access-server-pd)

Here (below) is how I would like to set it up

MYVAR="git@github.com:project/access-server-pd.git" 

NAME=${MYVAR%.*}  # retain the part before the colon
NAME=${NAME##*/}  # retain the part after the last slash
echo $NAME

I have it current set up with triple quotes on the pipeline script:

  stage('Git Clone') {
  MYVAR="$GIT_REPO"
  echo "$MYVAR"
  NAME="""${MYVAR%.*}"""
  echo "$NAME"

But I am receiving an unexpected token on "." error. How might I write this so that I can get this to work?

UPDATE: This command does the trick:

echo "git@github.com:project/access-server-pd.git" | sed 's#.*/\([^.]*\).*#\1#'

Now I just need to find the proper syntax to create a variable to store that value.


回答1:


In this case, it looks like using a few Groovy/Java methods on the String can extract the parts.

final beforeColon = url.substring(0, url.indexOf(':'))  // git@github.com
final afterLastSlash = url.substring(url.lastIndexOf('/') + 1, url.length()) // project/access-server-pd.git

This uses a few different methods:

  • public int String.indexOf(String str, int fromIndex)
  • public String String.substring(int beginIndex, int endIndex)
  • public int String.length()
  • public int String.lastIndexOf(String str)

You do need to be careful about the code you use in your pipeline. If it is sandboxed it will run in a protected domain where every invocation is security checked. For example, the whitelist in the Script Security Plugin whitelists all of the calls used above (for example, method java.lang.String lastIndexOf java.lang.String).

Performing String manipulation in your pipeline code is perfectly reasonable as you might make decisions and change your orchestration based on it.



来源:https://stackoverflow.com/questions/50029296/extracting-part-of-a-string-on-jenkins-pipeline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!