perl regular expressions and field search

Hello guys/gals,

i am sorry as this is probably very simply but i am slowly learning perl and need to convert some old korn shell scripts.

I need to be able to search a file line by line but only match a string at particular location on that line, for example character 20-30. So my file could look something like this:

apple orange apple
         apple potato apple
         tomato flower orange

i want to be able to search this file for string "orange" but i only want to search for this string at particular position, say from character 7-13. I am used to in bash i can use |awk '{print $2)' to get my second field ..but how would i do it in perl using regular expressions ?

Thanks a bunch

If you want to SPLIT a line into FIELDS as you say you do in bash, then look up perl's split() built in subroutine... On the other hand, if what you really want is to test the characters from positionX to positionY, then use perl's unpack() function. Once you split out your field by delimiter or position, then you can test it using regular expressions to see if it is the string you want...

I'm not going to do ALL the work for you :wink:

theeven

simply open file >
store each line of file in an array >
split each lines in fields >
print >

$file='./file.txt';
open(INFO,$file);
@lines=<INFO>;
close(INFO);

foreach $line (@lines)
{
@field=split(/ /,$line);
print "$field[1]\n";
}

theeven

Thanks guys, split looks pretty easy but i also research unpack. I might use it in the future as well, very flexible. Thanks again for your help.

Also look at the substr command, and determine which better suits your needs between unpack and substr.

Your first step is being sure what you need - search within certain columns, or searching by field.