Home > Back-end >  grep pattern from command output
grep pattern from command output

Time:06-14

I want to run the following in Linux via execute shell in jenkins.

when I run it directly in Linux, I get:

$ polyspace-access -list-project XX/YY -host MyHost -protocol http -login MyUsername -encrypted-password MyPassword
Connecting to MyHost 
Connecting as MyUsername
Get project list with the last Run Id
XX/YY RUN_ID 10
Command Completed

I can run the same command in Jenkins, but --

export RunID=`polyspace-access -list-project XX/YY -host MyHost -protocol http -login MyUsername -encrypted-password MyPassword`
echo "This is my RunID: $RunID"

... and here is the result:

15:06:59 This is my RuleID: Connecting to MyHost 15:06:59 Connecting as MyUsername 15:06:59 Get project list with the last Run Id 15:06:59 XX/YY RUN_ID 10 15:06:59 Command Completed

How can I read only the RUN_ID number from the results?

CodePudding user response:

You can do this with some groovy. Please check the following sample pipeline. I'm just echoing your output in the script block.

pipeline {
    agent any

    stages {
        stage('GetID') {
            steps {
                script {
                    string = sh(returnStdout: true, script: 'echo "15:06:59 This is RUN10X my RuleID: Connecting to MyHost 15:06:59 Connecting as MyUsername 15:06:59 Get project list with the last Run Id 15:06:59 XX/YY RUN_ID 10 15:06:59 Command Completed"').trim()
                    def runId = string.split("RUN_ID")[1].split(" ")[1]
                    echo "$runId"
                } 
            }
        }
    }
}

Note: You may need to improve the script part to handle error cases.

CodePudding user response:

If your shell has awk available, you could pipe the output through it to ask for the third field in the line that contains the text "RUN_ID":

runid=`polyspace-access -list-project XX/YY -host MyHost -protocol http -login MyUsername -encrypted-password MyPassword | awk '/RUN_ID/ { print $3 }'`
echo "This is my RunID: $runid"

You could adjust the pattern matching to be stricter if you know that XX/YY is a fixed string. You could also adjust the printing to $NF if there might be more than three fields but the desired number is always the last field.

CodePudding user response:

if you want to generalize it, such that "RUN_ID" has spaces around it, and always print out the last column, try :

# (broken apart for readability - it's one single string)

echo 'abc def -$314,159,265,358,979,323.84 XX/YY 2277118.822881188' 
     ' RUN_ID 3321928094887362347870319429489390175' | 

{m,g}awk   '$!NF=$(NF*=!_!~NF)' FS=' RUN[_]ID '
    gawk     '$_=$(NF*=!_<NF)'  FS=' RUN[_]ID '
    mawk '$!  NF=$--NF'         FS=' RUN[_]ID '

.

3321928094887362347870319429489390175
  • Related