learn_gnuawk icon indicating copy to clipboard operation
learn_gnuawk copied to clipboard

Q: 78/88 - Issues with reference solution

Open FabijanC opened this issue 1 year ago • 1 comments

Problem text

This is Q: 78/88 of awkexercises:

For the input file broken.txt, print all lines between the markers top and bottom. Assume that the input file cannot have two top markers without a bottom marker appearing in between and vice-versa.

Reference Solution

$ tac broken.txt | awk '/top/{f=0} f; /bottom/{f=1}' | tac

Input File

This is broken.txt:

top
3.14
bottom

---

top
1234567890
bottom
top
Hi there
Have a nice day
Good bye

Issues

From my understanding, if the first line is changed to any string not equal to, but containing top (e.g. stop), the reference solution will print 3.14 when it shouldn't.

Also, if the first line (i.e. the one with top) is completely removed, 3.14 will still be printed, when, from my understanding, it shouldn't be.

My Solution

Here's a solution which doesn't rely on external commands and doesn't have any of the issues above. Let me know if there are any issues with it. The solution could be shorter, but for the sake of clarity I used descriptive variable names and line breaks.

awk '
    /^top$/{collected=""; collecting=1}
    /^bottom$/{print collected; collecting=0}
    collecting{collected+=$0}
' broken.txt

FabijanC avatar Jun 09 '24 11:06 FabijanC