Re: cut -c18-31,49-51 in perl?
- From: anno4000@xxxxxxxxxxxxxxxxxxxxxxx (Anno Siegel)
- Date: 4 Jan 2006 20:05:43 GMT
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.
.
- References:
- cut -c18-31,49-51 in perl?
- From: Dan Jacobson
- cut -c18-31,49-51 in perl?
- Prev by Date: Re: Email Attachment Question: SMTP
- Next by Date: Re: getting error
- Previous by thread: Re: cut -c18-31,49-51 in perl?
- Next by thread: Re: cut -c18-31,49-51 in perl?
- Index(es):
Relevant Pages
|