×
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

how to find last word in a line??
2

how to find last word in a line??

how to find last word in a line??

(OP)
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

RE: how to find last word in a line??

# 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

RE: how to find last word in a line??

open(FILE, "file");
while(<FILE>)
{
   /^\b(.+?)\b.+?\b(.+?)\b$/g;
   print NEWFILE "$1 $2\n";
}
close(FILE);

adam@aauser.com

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login


Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close