-2

My sample dataset:

Date|Name|Subject|Presence
20200101|Aari|Maths|0
20200102|Aari|Maths|1
20200103|Aari|Maths|1
20200104|Aari|Maths|0
20200105|Aari|Maths|1
20200101|Aari|Science|1
20200102|Aari|Science|0
20200103|Aari|Science|0
20200104|Aari|Science|1
20200105|Aari|Science|1
20200101|Ben|Maths|0
20200102|Ben|Maths|0
20200103|Ben|Maths|1
20200104|Ben|Maths|1
20200105|Ben|Maths|1
20200101|Ben|Science|1
20200102|Ben|Science|0
20200103|Ben|Science|1
20200104|Ben|Science|1
20200105|Ben|Science|1

Consider "Date-Name-Subject" as a group, within this group need to print rows which had PRESENCE=0 in that row only if PRESENCE=1 in before and after row in this sorted group. In this case,20200101 and 20200105 shall not be considered for iteration as it will not have both before and after records for checking within the group.

My expected output for this sample data is:

20200104|Aari|Maths|0
20200102|Ben|Science|0

As only these records have before and after rows with PRESENCE=1 (within the GROUP)

.

Dhivya
  • 9
  • 1
  • 2
    Please post your current attempt – Marcin Orlowski Apr 30 '20 at 05:19
  • @Dhivya : Plesae clarify why you ask for a solution in _bash_. While this **can** be done in bash, other languages (awk, Perl, Ruby,...) are much more suitable for this task. – user1934428 Apr 30 '20 at 06:24
  • i m quite new to Bash and my attempt was trying doing nested FOR block. But that still didnt work. Awk and Perl can also be used, but i prefer to merge with existing Bash code. So, looking in the same means. – Dhivya Apr 30 '20 at 07:01

1 Answers1

1

You can do it in awk with the following:

BEGIN{
  FS="|";
}

NR>1{

  prevprev = prev;
  prev = curr;
  curr = $4;
  if (curr && !prev && prevprev) {
    print prevRow;
  }
  prevRow = $1 "|" $2 "|" $3
}

This can be invoked with cat file.txt | awk -f program.awk

Or you can embed the awk code in a "here document" in your bash script.

xdhmoore
  • 8,935
  • 11
  • 47
  • 90
  • Please don't teach [unnecessary uses of _cat_](https://stackoverflow.com/questions/11710552/useless-use-of-cat) – user1934428 Apr 30 '20 at 06:22