Re: cut -c18-31,49-51 in perl?



Dan Jacobson <jidanni@xxxxxxxxxxx> wrote in comp.lang.perl.misc:
> $ perldoc -q cut #no help, so asking here.
> How do I emulate UNIX's "cut -c18-31,49-51"?
> Certainly there is no one-liner possible unless I express the ranges
> differently?

Here is a way to do it with unpack(). The relation between the cut
specification and the corresponding template for unpack is made explicit.
The code also demonstrates that "cut" with the original specification
and the same data produces the same output.

In a one-off case one would probably create the template '@17a14 @48a3'
once manually (well, as often as it takes to get it right), and make it
a one-liner.

my $template; # for unpack
for ( [ 18, 31], [ 49, 51] ) { # "cut -c" specifications
my ( $first, $last) = @$_; # "cut" counts from 1
my $start = $first - 1;
my $length = $last - $first + 1;
$template .= ' ' if $template;
$template .= '@' . $start . 'a' . $length;
}
print "template: $template\n";

my $str; # collect DATA to feed into cut command
while ( <DATA> ) {
$str .= $_;
print unpack( $template, $_), "\n";
}
print "\n";

open my $cut, '| cut -c18-31,49-51';
print $cut $str;


__DATA__
0000000000111111111122222222223333333333444444444455555555556666666666
0123456789012345678901234567890123456789012345678901234567890123456789

Anno
--
If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers.
.



Relevant Pages

  • Re: Beatles Hit Songs?
    ... >>> If it's a faulty policy? ... > in an endless string of quoted messages just to add a one-liner at the ... instead of at the top or bottom your quip was buried smack in the middle. ...
    (rec.music.beatles)
  • Re: Multiple substr() exchange
    ... If you find yourself calling substr() on the same string a lot, ... using unpack(). ... You certainly *could* use a regex (and probably a tricky split too), ... "Reply" at the bottom of the article headers. ...
    (comp.lang.perl.misc)
  • Re: single-byte values
    ... > now I'm hip. ... Well, as you already noticed yourself, Perl is not C. ... But that's mainly because I like unpack() a lot. ... the unpacktemplate would be ...
    (comp.lang.perl.misc)
  • Re: Perhaps not, was Re: A suggestion for responding to posts on s.a.a.... please put the quotes at
    ... Brian Tung wrote: ... rather than a voluminous quote followed by a one-liner at the bottom. ... the big deal is editing down. ...
    (sci.astro.amateur)
  • Re: unpack() help
    ... >I have the .h file of a program that spits out a data file which is Binary Output. ... >I thought I could use unpack to read the data, and I am having no success. ... ># this is the template we're going to feed to unpack ...
    (perl.beginners)