For Programmers: Free Programming Magazines  


Home > Archive > AWK > December 2005 > AWK: simple how to supply a list of fields









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author AWK: simple how to supply a list of fields
janvdberg@gmail.com

2005-12-12, 6:56 pm

Im looking for a way to shorten this:
awk '{print
$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17
,$18,$19,$20,$21,$22,$23,$24,$25}'
file

So how can I print all fields (7 to 31) I've tried: awk '{print
$7-$25}' file.
But this subtracts field 31 from 7.

Ed Morton

2005-12-12, 6:56 pm



janvdberg@gmail.com wrote:

> Im looking for a way to shorten this:
> awk '{print
> $7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17
,$18,$19,$20,$21,$22,$23,$24,$25}'
> file
>
> So how can I print all fields (7 to 31) I've tried: awk '{print
> $7-$25}' file.
> But this subtracts field 31 from 7.
>


awk '{for (i=7;i<=25;i++){printf "%s%s",sep,$i;sep=FS} print ""}'

or you can use an RE to delete fields, e.g.: to delete all fields up to
field N, preserving input formatting.
gawk --re-interval 'sub(/ ^[[:space:]]*([^[:space:]]*[[:space:]]*)
{N}/,"")'

The number "N" within the "{...}" is the number of initial fields to delete.

Note that "gensub()" is not available with "--posix" but it is available
with "--re-interval" so if you need to use an interval expression (e.g.
{1,} or {8} or {2,4}) with gensub() then you must use --re-interval
rather than --posix so --re-interval is generally the preferred method.

Regards,

Ed.
janvdberg@gmail.com

2005-12-13, 3:56 am

Thanks for your first suggestion; it works!
Incredible that something so seemingly simple has to be done in such a
rather complex manner.

Kenny McCormack

2005-12-13, 3:56 am

In article <1134464211.072594.35900@g47g2000cwa.googlegroups.com>,
<janvdberg@gmail.com> wrote:
>Thanks for your first suggestion; it works!


(the usual comment about Googlers not providing context)

>Incredible that something so seemingly simple has to be done in such a
>rather complex manner.


Ed's:

awk '{for (i=7;i<=25;i++){printf "%s%s",sep,$i;sep=FS} print ""}'

Can be simplified to:

{for (i=7;i<=25;i++) printf "%s%s",$i,i==25 ? ORS : FS}

Or even:

BEGIN {ORS=FS}
{for (i=7;i<25;i++) print $i;printf "%s\n",$i}

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com