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

Brian Gibson bwg1974 at yahoo.com
Thu Oct 7 00:48:59 MDT 2010


not necessarily the fewest strokes but it is one line (your mail client may 
break the line)

COMMAND:
$ echo "this that1 that2 that3 theotherthing" | ruby -e 'puts 
STDIN.read.split().slice(1..-1).join(",").split(/,(?!.*,)/)'

OUTPUT:
that1,that2,that3
theotherthing

******************************

1) STDIN.read = get standard input from piped echo
2) split() = convert string to array splitting it on whitespace
3) slice(1..-1) = return an array without the first item (range = 2nd item to 
last item)
4) join(",") = return a string by joining the array items using a comma as glue
5) split(/,(?!.*,)/) = split the new string on the last comma (see credits 
below)

ruby implicitly returns the last returned value of any code block, in this case 
the 2-item array, which goes to STDOUT as two lines.  With some minor changes, 
this can be setup to accept a text file.

credit for the secret sauce goes to
http://frightanic.wordpress.com/2007/06/08/regex-match-last-occurrence/
http://www.perlmonks.org/?node_id=518444



----- Original Message ----
From: chris fedde <chris at fedde.us>
To: CLUE technical discussion <clue-tech at cluedenver.org>
Sent: Thu, October 7, 2010 12:32:11 AM
Subject: Re: [clue-tech] [spam?] text processing howto

On Wed, Oct 6, 2010 at 8:38 PM, Collins Richey <crichey at gmail.com> wrote:
> On Wed, Oct 6, 2010 at 6:36 PM, Collins Richey <crichey at gmail.com> wrote:
>
>>
>> You can do the same thing in two lines of perl.
>
> Well, I lied about 2 lines; I forgot about printing. Anyway, in the
> much maligned perl code ...
>
> #!/usr/bin/perl
> # string has imbedded tabs and varying number of spaces
> $string = "this          that1   that2   that3          theotherthing";
> @list = split(/\s+/, $string);
> foreach $item (@list) {
>        print "$item\n";
> }
> # and if you want just the otherthing
> print "$list[$#list]\n"
>

Golf is a popular game among some parts of the perl community.
Getting the task done in the fewest number of (key) strikes. :-)
These solutions take advantage of default behaviors of the split
function.

# the last item of the list
perl -le '$_= "this          that1   that2   that3
theotherthing"; print +(reverse split)[0]'

# all the items one per line
perl -le '$_= "this          that1   that2   that3
theotherthing"; print for split'
_______________________________________________
clue-tech mailing list
clue-tech at cluedenver.org
http://cluedenver.org/mailman/listinfo/clue-tech



      


More information about the clue-tech mailing list