Search code examples
shellscriptingcygwin

Remove some text with shell scripts?


I wanted to get some help on how I can use cygwin, which has bash to shell script the following:

I have a txt file that contains the following:

action "action1"
  reset
  type xformbin
  http-method-limited POST
  http-method-limited2 POST
exit

action "action2"
  reset
  admin-state disabled
  type results
  http-method-limited POST
  http-method-limited2 POST
exit

action "action3"
  reset
  admin-state disabled
  type setvar
  http-method-limited POST
  http-method-limited2 POST
exit

I was hoping a shell script could be written to remove the block where admin-state = disabled?

So, I'm hoping I can iterate through the txt file and if admin-state = disabled, remove everything between "action" and "exit" from that particular block.

I would expect the following final results from the sample text:

action "action1"
  reset
  type xformbin
  http-method-limited POST
  http-method-limited2 POST
exit

Thank you.


Solution

  • So you want the whole block ignored if it has 'disabled' in the middle, but printed if it does not.

    sed -n '
      /action/,/exit/ {
      /action/ { x; d; }
      H;
      /exit/ { x;
        /disabled/ d;
        p;         d;
      }
    }' x
    

    This will do nothing unless in a block from action to exit. In those -

    If a line has action, store it and delete the pattern space to trigger the next read.

    Otherwise append the line to the stored hold space.

    If the line had exit,

    • swap the hold space into the pattern space
    • if the collected pattern has disabled, delete it to trigger reading the next record;
    • if not, print it, then delete it to trigger reading the next record.

    The output:

    $: sed -n '
      /action/,/exit/ {
        /action/ { x; d; }
        H;
        /exit/ { x;
          /disabled/ d;
          p;         d;
        }
      }' infile
    action "action2"
    reset
    admin-state enabled
    type xform
    http-method GET
    http-method-limited POST
    http-method-limited2 POST exit
    

    Hope that helps.