Coogie7
Coogie7

Reputation: 199

Shell Script to Replace or Insert Lines of Text in File

I wrote a Shell script to replace text in the Jenkinsfiles of a large number of repos. I had used this to add on a parameter to a single line of text. However, now I need to insert a line of text before and after an existing command in the Jenkinsfiles. I don't have too much shell experience and could use some help.

Here is the Jenkinsfile text before:

sh "chmod +x increment.sh"
def result = sh returnstdout:true, script: "./increment.sh '${Version}' '${ReleaseVersion}' '${GitRepoURL}' '${CutRelease}' '${Branch}' '${JiraID}'"
//echo "$result"    

I need to add the following before the "def result" line:

sshagent(['gitssh']) {

and then add a closing curly bracket after the "def result" line:

}

I need the end result to be:

sh "chmod +x increment.sh"
sshagent(['gitssh']) {
    def result = sh returnstdout:true, script: "./increment.sh '${Version}' '${ReleaseVersion}' '${GitRepoURL}' '${CutRelease}' '${Branch}' '${JiraID}'"
}
//echo "$result"    

I actually don't care about keeping the commented out echo command if that makes it more difficult, but it is just to show what I have surrounding the "def result" line.

How can I accomplish this end result?

If it helps, I previously was adding new parameters at the end of the "def result" line with this code:

if [ -e Jenkinsfile ]
then
    sed -i -e "s/\${Branch}/\${Branch}\' \'\${JiraID}/g" Jenkinsfile
fi

Note: I am on a Mac.

Code so far:

file=repos_remaining.txt
while IFS="," read -r repoURL repoName; do
echo $repoURL
cd ..
echo $repoName
cd $(echo $repoName | tr -d '\r')
file=repos_remaining.txt    
if [ -e Jenkinsfile ]
then
    # sed -i -e $"s/def result/sshagent([\'gitssh\']) {\
    #   def result/g" Jenkinsfile
fi

# git add "Jenkinsfile"
# git commit -m "Added JiraID parameter to Jenkinsfile"
# git push origin master
done < "$file"

Upvotes: 0

Views: 291

Answers (1)

Shawn
Shawn

Reputation: 52549

As with most cases where people want to automate the editing of a file, I suggest using ed:

ed -s Jenkinsfile <<'EOF'
/^def result/i
sshagent(['gitssh']) {
.
.+1a
}
.
w
EOF

The commands in the heredoc tell ed to move the cursor to the first line starting with def result, insert a line above it, append a line after it, and finally write the modified file back to disc.

Upvotes: 1

Related Questions