Extract fields of data in Perl (split, awk)

Home > Search
  by

In Linux, the awk command is used to only display certain fields of output. In this context, a field is a string of data, delimited by whitespace. For example, the df -h command has fields of data delimited by whitespace.

 


Split a variable

In Perl, the split command can be used to only display certain fields of data. For example, let's say the $greetings variable has the following text.

$greeting = "Hello World How are you today";

 

Each string in the greetings variable can be split into it's own item in an array.

@strings = split / /, $greeting;

 

Dumper can be used to verify that the variable can be split into an array.

use Data::Dumper;
print Dumper \@strings;

 

The dumper output should be:

$VAR1 = [
          'Hello',
          'World',
          'How',
          'are',
          'you',
          'today'
        ];

 

Likewise, the entire array can be printed.

print @strings;

 

Or, a single value in the array can be printed.

print @strings[0];

 


Split a file

Let's say example.txt has the following text.

Hello World How are you today

 

The following Perl script will associate each field of data with a unique variable. In this example, $field0 would have the value "Hello", $field1 would have the value "World", and so on.

open(FH, '<', example.txt);

while (<FH>) {
  $field0 = ((split ' ')[0]);
  $field1 = ((split ' ')[1]);
  $field2 = ((split ' ')[2]);
  $field3 = ((split ' ')[3]);
  $field4 = ((split ' ')[4]);
  $field5 = ((split ' ')[5]);
}

close(FH);

 

Each variable can then be printed.

print "$field0 \n";
print "$field1 \n";
print "$field2 \n";
print "$field3 \n";
print "$field4 \n";
print "$field5 \n";

 

Which would produce the following output.

Hello
World
How
are
you
today

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments