Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Q: 78/88 - Issues with reference solution #12

Open
FabijanC opened this issue Jun 9, 2024 · 1 comment
Open

Q: 78/88 - Issues with reference solution #12

FabijanC opened this issue Jun 9, 2024 · 1 comment

Comments

@FabijanC
Copy link

FabijanC commented Jun 9, 2024

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
@learnbyexample
Copy link
Owner

Thanks!

Regarding matching top and bottom as whole lines, that wasn't a requirement - I would've emphasized word/line matching in such cases. But still, might be better to make it clearer.

Regarding the case of bottom appearing first in the file before a top marker - I hadn't considered that. I'll have to either indicate that won't be possible or change the scope of the question.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants