2

The following awk script will add an entry SAMPLE to block NOTES. I have multiple blocks with the same name. What needs to be changed in this command to add the entry SAMPLE to first block NOTES only?

a class.txt with following content.

[serverClass:NOTES:new]
 whitelist.0=TEST
 whitelist.1=FRIDAY
 whitelist.2=SPOON
 whitelist.3=GAME29

[serverClass:NOTES]
 whitelist.0=TEST
 whitelist.1=FRIDAY
 whitelist.2=SPOON
 whitelist.3=GAME29

[serverClass:NOTES:new23]
 whitelist.0=TEST
 whitelist.1=FRIDAY
 whitelist.2=SPOON
 whitelist.3=GAME29sdf

after running this command

awk -vRS= -vORS='\n\n' '
  BEGIN{z="whitelist.0=SAMPLE";FS="\n"}
  /NOTES/{
    if (/[0-9]=/){
      split($NF, a, /[.=]/);
      sub(/0/, a[2]+1, z)
    }
    sub (/$/,"\n"z ,$0)
  };1' class.txt

output:

[serverClass:NOTES:new]
 whitelist.0=TEST
 whitelist.1=FRIDAY
 whitelist.2=SPOON
 whitelist.3=GAME29
 whitelist.4=SAMPLE    <-------

[serverClass:NOTES]
 whitelist.0=TEST
 whitelist.1=FRIDAY
 whitelist.2=SPOON
 whitelist.3=GAME29
 whitelist.4=SAMPLE    <-------

[serverClass:NOTES:new23]
 whitelist.0=TEST
 whitelist.1=FRIDAY
 whitelist.2=SPOON
 whitelist.3=GAME29sdf
 whitelist.4=SAMPLE    <-------

what need to be changed in above awk command to add to the block match [serverClass:NOTES] only?

expected:

[serverClass:NOTES:new]
 whitelist.0=TEST
 whitelist.1=FRIDAY
 whitelist.2=SPOON
 whitelist.3=GAME29

[serverClass:NOTES]
 whitelist.0=TEST
 whitelist.1=FRIDAY
 whitelist.2=SPOON
 whitelist.3=GAME29
 whitelist.4=SAMPLE    <-------  should be

[serverClass:NOTES:new23]
 whitelist.0=TEST
 whitelist.1=FRIDAY
 whitelist.2=SPOON
 whitelist.3=GAME29sdf
2
  • Please don't change the requirements of your question after posting it. This is not the same question you had asked before. You need to post a new question each time you need something different.
    – terdon
    Mar 1, 2016 at 19:16
  • OP, in this case you should simply use /NOTES]/ instead of /NOTES/. Mar 1, 2016 at 19:19

1 Answer 1

2

The simplest approach is to use a variable and set its value to 1 the first time NOTES is found. Then, tell your script to only add the new entry if the variable is not 1. For example:

awk -vRS= -vORS='\n\n' '
  BEGIN{z="whitelist.0=SAMPLE";FS="\n"}
  /NOTES/ && flag!=1{
    if (/[0-9]=/){
      split($NF, a, /[.=]/);
      sub(/0/, a[2]+1, z);
      flag=1;
    }
    sub (/$/,"\n"z ,$0)
  };1' infile
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.