0

i am trying to delete some records from input file.

list.txt
tag1,slate1,flag1,status0,8,1
tag2,slate2,flag2,status0,2,3
tag1,slate1,flag1,status1,8,1
tag2,slate2,flag2,status1,2,3
tag1,slate1,flag1,status0,0,1
tag2,slate2,flag2,status1,2,3
tag1,slate1,flag1,status1,1,2
tag2,slate2,flag2,status1,1,2
tag1,slate1,flag1,status1,3,4

Expected output: list.txt

tag2,slate2,flag2,status0,2,3
tag2,slate2,flag2,status1,2,3
tag1,slate1,flag1,status0,0,1 -> deleted records above this and matching [tag1,slate1,flag1]
tag2,slate2,flag2,status1,2,3
tag1,slate1,flag1,status1,1,2
tag2,slate2,flag2,status1,1,2
tag1,slate1,flag1,status1,3,4

I tried using code:

sed '/tag2,slate2,flag2,status0/d' list1.txt

But this delete records tag1,slate1,flag1,status0,0,1, tag1,slate1,flag1,status1,1,2, etc.. also.

is there any way to stop sed when record reached 'tag1,slate1,flag1,status0,0,1 ?

and 'tag1,slate1,flag1,status0' not found then no need to remove any records matching 'tag1,slate1,flag1'

Any suggestions to get output.

5
  • 1
    What is the rule for above this -> tag1,slate1,flag1,status0,0,1 ? the whole line?
    – pLumo
    Mar 19 at 7:21
  • And would awk be okay, too?
    – pLumo
    Mar 19 at 7:22
  • awk also okay for this
    – K Soumya
    Mar 19 at 7:36
  • 1
    all record matching 'tag1,slate1,flag1' need to delete till we got last matching record 'tag1,slate1,flag1,status0' we need to stop deleting records matching 'tag1,slate1,flag1'
    – K Soumya
    Mar 19 at 7:37
  • 1
    aah, the last matching pattern should stay, okay. Please edit your question and add this information.
    – pLumo
    Mar 19 at 7:38
0

You can use awk:

awk '
NR == FNR && /tag1,slate1,flag1,status0/{last_matching=FNR}
NR != FNR && FNR<last_matching && /tag1,slate1,flag1/{next}
NR != FNR
' list.txt list.txt

awk reads the file twice.

  • On the first run (NR == FNR) ...
    • we save the last matching FNR (= record/line number of the file) in a variable.
  • On the second run (NR != FNR) ...
    • we will skip all matching lines (--> /tag1,slate1,flag1/{next})
    • but only until last_matching(--> FNR<last_matching).
    • and print all remaining lines with NR != FNR.
2
  • Thank you working fine.
    – K Soumya
    Mar 19 at 8:11
  • one more thing if 'tag1,slate1,flag1,status0' not found then no need to remove any records matching 'tag1,slate1,flag1' , Can you adjust code in this way please?
    – K Soumya
    Mar 19 at 8:14
0

Using sed stream editor utility we can do as follows:

sed -ne ':top
/^tag1,slate1,flag1,status0,0,1$/!{
  /^tag1,slate1,flag1,/!p;n
  btop
}
:n;p;n;bn
' list.txt
  • Until we see the target line we keep printing non matching lines.
  • As soon as the target line is met, we keep printing all lines until the file is exhausted.

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.