Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I print only certain fields in a space separated file?

Tags:

split

field

perl

I have a file containing the following content 1000 line in the following format:

abc def ghi gkl

How can I write a Perl script to print only the first and the third fields?

abc ghi
like image 976
Muhammad Hewedy Avatar asked Mar 19 '10 16:03

Muhammad Hewedy


3 Answers

perl -lane 'print "@F[0,2]"' file
like image 95
mob Avatar answered Oct 21 '22 03:10

mob


If no answer is good for you yet, I'll try to get the bounty ;-)

#!/usr/bin/perl
# Lines beginning with a hash (#) denote optional comments,
# except the first line, which is required,
# see http://en.wikipedia.org/wiki/Shebang_(Unix)

use strict;   # http://perldoc.perl.org/strict.html 
use warnings; # http://perldoc.perl.org/warnings.html

# http://perldoc.perl.org/perlsyn.html#Compound-Statements
# http://perldoc.perl.org/functions/defined.html
# http://perldoc.perl.org/functions/my.html
# http://perldoc.perl.org/perldata.html
# http://perldoc.perl.org/perlop.html#I%2fO-Operators
while (defined(my $line = <>)) {
    # http://perldoc.perl.org/functions/split.html
    my @chunks = split ' ', $line;
    # http://perldoc.perl.org/functions/print.html
    # http://perldoc.perl.org/perlop.html#Quote-Like-Operators
    print "$chunks[0] $chunks[2]\n";
}

To run this script, given that its name is script.pl, invoke it as

perl script.pl FILE

where FILE is the file that you want to parse. See also http://perldoc.perl.org/perlrun.html. Good luck! ;-)

like image 45
codeholic Avatar answered Oct 21 '22 05:10

codeholic


That's really kind of a waste for something as powerful as perl, since you can do the same thing in one trivial line of awk.

awk '{ print $1 $3 }'

like image 32
T.E.D. Avatar answered Oct 21 '22 03:10

T.E.D.