title: Shell Script to Replace or Insert Lines of Text in File
body: <p>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.</p>
  
  <p>Here is the Jenkinsfile text before:</p>
  
  <pre><code>sh "chmod +x increment.sh"
  def result = sh returnstdout:true, script: "./increment.sh '${Version}' '${ReleaseVersion}' '${GitRepoURL}' '${CutRelease}' '${Branch}' '${JiraID}'"
  //echo "$result"    
  </code></pre>
  
  <p>I need to add the following before the "def result" line:</p>
  
  <pre><code>sshagent(['gitssh']) {
  </code></pre>
  
  <p>and then add a closing curly bracket after the "def result" line:</p>
  
  <pre><code>}
  </code></pre>
  
  <p>I need the end result to be:</p>
  
  <pre><code>sh "chmod +x increment.sh"
  sshagent(['gitssh']) {
      def result = sh returnstdout:true, script: "./increment.sh '${Version}' '${ReleaseVersion}' '${GitRepoURL}' '${CutRelease}' '${Branch}' '${JiraID}'"
  }
  //echo "$result"    
  </code></pre>
  
  <p>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.</p>
  
  <p><strong>How can I accomplish this end result?</strong></p>
  
  <p>If it helps, I previously was adding new parameters at the end of the "def result" line with this code:</p>
  
  <pre><code>if [ -e Jenkinsfile ]
  then
      sed -i -e "s/\${Branch}/\${Branch}\' \'\${JiraID}/g" Jenkinsfile
  fi
  </code></pre>
  
  <p>Note: I am on a Mac.</p>
  
  <p>Code so far:</p>
  
  <pre><code>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 &lt; "$file"
  </code></pre>