learn_gnuawk icon indicating copy to clipboard operation
learn_gnuawk copied to clipboard

Regexp exercise 15): solution improvement

Open FabijanC opened this issue 1 year ago • 4 comments

First of all, thanks for the great tutorial and the CLI app for exercising!

Sorry, I accidentally pressed Submit before finishing my issue. Here's the rest.

In question 21/88, i.e. exercise 15) of the Regular Expressions section, the proposed solution is this: https://github.com/learnbyexample/learn_gnuawk/blob/96b8442fc372303f1be838bf01a2210ded152b58/exercises/Exercise_solutions.md?plain=1#L244-L250

Isn't this a shorter solution:

awk '/(.*ar.*){3,}/{print gensub(/ar/, "X", NF-2)}' patterns.txt

Also, is the phrasing "last but second" correct? I was rather confused. Is the intended meaning the same as that of the word "antepenultimate"?

FabijanC avatar Apr 18 '24 15:04 FabijanC

There were some bugs in the original awk code I provided, they occurred because I had to re-write them here in the issue as I couldn't copy-paste them. The CLI app doesn't allow selecting any content. I see this as an issue - should I open a new one here on GitHub? Or is that inherent to that kind of application?

Anyway, my awk code should now be bug-free and yielding the same output as yours.

FabijanC avatar Apr 18 '24 16:04 FabijanC

Your solution won't work for input like par:car tar-far;Cart since you are making use of fields. The question is intended as a search and replace problem. I should probably add such an input line or make the question clearer.

Regarding last-but-second:

par car tar far Cart
                 ^^last
             ^^last but one
         ^^last but two 

Regarding the CLI app, I don't know if there's a way to select content. I could probably add a button/short-cut to copy the content in the Input box, but other than that I doubt I'll be able to add other features. I'm using a third-party Python module for that app and I'm not really familiar with it.

learnbyexample avatar Apr 19 '24 03:04 learnbyexample

Building upon your idea, I think awk -F'ar' 'NF>3{print gensub(FS, "X", NF-3)}' will work. Will update if I can think of case where this'd fail.

learnbyexample avatar Apr 19 '24 04:04 learnbyexample

Thanks for the reply! About an hour after asking I realized that I was making use of fields, but wasn't at the computer to reply. Anyway, I'm still a newcomer to awk, so I'll try forgiving myself this mistake.

Here's an interesting link regarding "last but second".

FabijanC avatar Apr 19 '24 06:04 FabijanC