Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to find last word in a line?? 2

Status
Not open for further replies.

rao12

IS-IT--Management
Jan 10, 2001
9
0
0
US
Hi,

I have a text file with each line having variable number of words..
how do i print the first few words and last word of a line in to an output file.
I was doing with $NF for the last feild in shell scripts how do i do it in perl.

sample text file
====================
hgahgdhsgd hgshdgshd jhkjjkj lklk 9898
ghsgh t6523 8787 87jhj jhjshjhh
jjkjkj hjhjjhh 0000

i would like first few words and the last word in an output file to process further.


Thanks
Rao
 
# with lines in @lines

foreach $line (@lines)
{
$line =~ /^(.*?\b.*?\b).*\b(.*?\b.*?)$/;
$first_two_words = $1;
$last_two_words = $2;
}


The up caret pins the regex to the start of the line. A dot (.) is a wild card. A dot followed by a star is any number of wild cards. A dot star question_mark \b is any number of wild cards up to the next word boundary (\b). There is a .* in the middle with no ? that will suck up the middle of the line. The dollar sign at the end pins the reges match to the end of the string(line).

'just one way.
'hope this helps.


keep the rudder amid ship and beware the odd typo
 
open(FILE, "file");
while(<FILE>)
{
/^\b(.+?)\b.+?\b(.+?)\b$/g;
print NEWFILE &quot;$1 $2\n&quot;;
}
close(FILE); adam@aauser.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top