[clue-tech] [spam?] text processing howto

David L. Anselmi anselmi at anselmi.us
Wed Oct 6 19:34:01 MDT 2010


Jim Ockers wrote:
> Hi David,
>
> [ockers at agadez ~]$ echo "this that1 that2 that3 theotherthing" | awk
> '{print $NF}'
> theotherthing
>
> [ockers at agadez ~]$ echo "this that1 that2 that3 theotherthing" | awk
> '{print $2 "," $3 "," $4}'
> that1,that2,that3

So this doesn't quite handle variable numbers of "thats".  Of course it could be done in a loop ($2 
- $NF-1 are the thats and $NF is the theotherthing).

Without loops, try this:

echo "this that1 that2 that3 that4 theotherthing" |
   awk '{OFS="," ; a = $NF; $1 = "" ; NF -=1 ; sub(OFS, "") ; print $0 " " a }'

So that's like 6 lines of AWK.  In Perl:

echo "this that1 that2 that3 that4 theotherthing" |
   perl -lne '@a = split; print(join(",", @a[1 .. $#a - 1]) . " $a[-1]")'

Which is maybe 3 or 4 lines.

Dave


More information about the clue-tech mailing list