sed + replace only the second match word

58

Solution 1

to change only the second match word ( to replace Allow,Deny with Deny,Allow )

sed solution:

Sample tmp_file:

Allow,Deny
Allow,Deny
Allow,Deny
Allow,Deny

sed ':a;N;$!ba; s/Allow,Deny/Deny,Allow/2' tmp_file

The output:

Allow,Deny
Deny,Allow
Allow,Deny
Allow,Deny

Solution 2

Another sed solution.

sed '0,/Allow/!{0,/Allow/s/Allow/Deny/}' /tmp/file

Here we match the first Allow then we ignore the substitution for the first Allow we come across and substitute the next line.

To give an idea, the following would substitute the second and fourth since we used N;

sed '0,/Allow/!{N;/Allow/s/Allow/Deny/}'

Or using awk:

awk '/Allow/{c++; if (c==2) { sub("Allow","Deny")}}1'

We match Allow then keep a counter c. If this matches the 2 second occurrence then we substitute it.

Share:
58

Related videos on Youtube

user3601857
Author by

user3601857

Updated on September 18, 2022

Comments

  • user3601857
    user3601857 over 1 year

    I have a executor service, where the thread runs 2-3 multiple process on the context object , and logs the state into the database, after each process is completed. Current code defines try and catch block after each logging statement , so that any database exceptions can be handled , and the worker moves to next process.

    Is there a design pattern, or a more graceful way of doing this. The code has multiple try and catch blocks inside a single function which is not readable

    Code snippet for example:

    completePayment() {
    
    validateAttribute1 ();
    try {
    logResultToDatabase() ;
    //calls the entity manager to persist
    }
    catch (Exception e ) {
    //do Nothing , continue to validateAttribute2
    }
    validateAttribute2 ();
    try {
    logResultToDatabase() ;//calls the entity manager to persist
    }
    catch (Exception e ) {
    //do Nothing , continue to doPayment
    }
    doPayment();
    try {
    logResultToDatabase();
    }
    catch (Exception e ) {
    //do Nothing.
    }
    }
    
    • JB Nizet
      JB Nizet over 7 years
      Don't describe the code. Post it.
    • user3601857
      user3601857 over 7 years
      @jb-nizet - Added a sample code snippet to explain the problem