tags:

views:

441

answers:

3

I saw once a quick and dirty Perl implementation for the cut and paste linux commands. It was something like perl 'print "$F1"' filename to substitute a cut -f1 filename command

Can someone tell me how was this Perl way? Specifically, I'm interested because this, unlike cut/paste, will work the same also in Windows environments.

+1  A: 

For cut: I think you are looking for the perl -ane solution (the -e executes the following code, the -an applies @F = split (/\t/,$line) to every line in the file). So something like:

perl -ane 'print "$F[0]\t$F[1]\n"' file

which is identical to:

cut -f1,2 file

For paste, I'm not sure how you can do this, but I think the perl -ane can take multiple files as input.

Thrawn
Note that cut drops the newline from the final field but Perl doesn't. The expression should probably be 'chomp(@F); print "$F[0]\t$F[1]\n"' to fix that.
jamessan
`paste` is more work. See http://stackoverflow.com/questions/1636755/how-many-different-ways-are-there-to-concatenate-two-files-line-by-line-using-per for several possible implementations
mobrule
+3  A: 

cut

perl -alpe'$_=$F[0]'
perl -alpe'$_="@F[1..3]"'

To give a custom input separator,

perl -F: -alpe'$_=$F[0]'

To change the output separator,

perl -F: -alpe'$"=":";$_="@F[1..3]"'

To grep while you're at it,

perl -alne'print$F[0]if/blah/'

paste

Not quite as easy.

#!/usr/bin/perl
for (@ARGV ? @ARGV : qw(-)) {
    if ($_ eq '-') {push @files, *STDIN}
    else {open $files[@files], '<', $_}
}
while (grep defined, (@lines = map scalar <$_>, @files)) {
    chomp @lines;
    print join("\t", @lines), "\n";
}
ephemient
+3  A: 

Do you know about the Perl Power Tools? They are implementations of your favorite unix commands, but done in Perl. If you have Perl, you can have your favorite commands without acrobatics on the command line. PPT has both cut and paste.

Although many people pointed you to some perl switches, they forget to link to perlrun which explains them all.

brian d foy
++! The PPT are an amazing resource. They can be very handy if you are on a win32 platform, and they demonstrate some interesting techniques.
daotoad