0

I have a log.txt file.The content of the file as below:

Content of the file as below:

properties{
set properties()
}

buildPipeline()
defPipeline(){
execute()
}

Now I have to insert below line just before buildPipeline():

def testbranch= 'feature'
if(env.BRANCH_NAME.startswith(testbranch)){
properties([pipelinetriggers([cron('0 */2 * * 1-5')]),])
}

I tried below .But it is inserting the statements at the end of the file:

sed -i -e "$adef testbranch= 'feature'" log.txt
sed -i -e "$aif(env.BRANCH_NAME.startswith(testbranch)){" log.txt
sed -i -e "$aproperties([pipelinetriggers([cron('0 */2 * * 1-5')]),])" log.txt
sed -i -e "$a}" log.txt

Expected output:

properties{
set properties()
}
def testbranch= 'feature'
if(env.BRANCH_NAME.startswith(testbranch)){
properties([pipelinetriggers([cron('0 */2 * * 1-5')]),])
}
buildPipeline()
defPipeline(){
execute()
}
miken32
  • 42,008
  • 16
  • 111
  • 154
raksha c
  • 9
  • 2
  • `$` means the last line, why are you using that if you don't want it to add at the end? – Barmar Feb 08 '23 at 17:21
  • Modifying your code with `sed` is hard and brittle. Change the code so that it takes different branches depending on a configuration setting or command-line option. – tripleee Feb 08 '23 at 19:23

2 Answers2

0

This sed command should do the job:

sed -i "
/buildPipeline()/i\\
def testbranch= 'feature'\\
if(env.BRANCH_NAME.startswith(testbranch)){\\
properties([pipelinetriggers([cron('0 */2 * * 1-5')]),])\\
}" log.txt

Note: This is for GNU sed. BSD sed requires the extension for the backup file with -i


Edit after the comment by the OP, which requests that insertion must take place only on the first occurrence of buildPipeline().

If you know the buildPipeline() won't occur on the first line of log.txt:

sed -i "
1,/buildPipeline()/!b
/buildPipeline()/i\\
def testbranch= 'feature'\\
if(env.BRANCH_NAME.startswith(testbranch)){\\
properties([pipelinetriggers([cron('0 */2 * * 1-5')]),])\\
}" log.txt
M. Nejat Aydin
  • 9,597
  • 1
  • 7
  • 17
  • Hi @M. Nejat Aydin, Thank you so much.The insertion is working.But i found that this buildPipeline() is getting repeated in the file multiple times and I want the insertion only before the 1st match.With above ,it is inserting before every match.How to restrict the entry only for the 1st match.Please help!!!Totally new to shell:-( – raksha c Feb 09 '23 at 11:26
  • @rakshac Read the updated answer. – M. Nejat Aydin Feb 09 '23 at 13:30
0

If ed is available/acceptable, something like:

#!/bin/sh

ed -s log.txt <<-'EOF'
/properties{/;/buildPipeline()/-,c
def testbranch= 'feature'
if(env.BRANCH_NAME.startswith(testbranch)){
properties([pipelinetriggers([cron('0 */2 * * 1-5')]),])
}
.
,p
Q
EOF

  • Change Q to w if in-place editing is required.
  • Remove the ,p to silence the output to stdout
Jetchisel
  • 7,493
  • 2
  • 19
  • 18