[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: OT: string manipulation. sed? gawk? other? how?



On 10/11/2011 03:20 PM, John L. Cunningham wrote:
> johnc@infotech:~$ cat lazydog.awk
> /^The lazy dog/{
>          if ( count<  1 ){
>                  print "The lazy dog is my favorite."
>                  count++
>                  next
>          } else {
>                  next
>          }
> }
> {
>          print
> }

This works, but for those that are interested, and at the risk of making
the script harder for some people to read, it can be simplified in a
number of ways.

1. The "next" can be pulled out of the loop (required on both branches)
2. The count++ can be pushed up into the condition (post-increment operator)
3. The count can be directly compared to zero rather than as <1
4. The count can be renamed k (fewer characters, and I'm "lazy")
5. The {print} can be "simplified" to a true expression (default is print)

The result is this one-liner, which can be fed stdin or a file, and its
output can be written whereever you require. (Note that this removes
the need for the lazydog.awk file.)

awk '/^The lazy dog/{if(!k++){print"The lazy dog is my favourite."};next}1'

:-)
Chris


Reply to: