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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Extracting part of string 2

Status
Not open for further replies.

nappaji

Programmer
Mar 21, 2001
76
US
Hello,
I am new to awk and an trying to extract a part of a string.

The sting has a delimiter of "_" and I want to extract the string before the last "_".

For ex: if I have

abc_def_ghi_2

I need to extract

abc_def_ghi.

Can it be done in a single awk statement.

Please help.
Thanks
 
Hi nappaji,

Here are two ways. One in awk, one in nawk.

nawk 'BEGIN{FS = OFS = "_"}{$NF = "" ; sub(/_$/,"") ; print}' infile > outfile

awk 'BEGIN{FS = OFS = "_"}{$NF = "" ; line = substr($0,1,length($0)-1) ; print line ; next}' infile > outfile

Hope this helps you.


flogrr
flogr@yahoo.com

 

Hello, nappaji and flogrr!

Nice solutions, flogrr.

This is awk-solution with for loop (and littlebit longer):

awk 'BEGIN { FS = &quot;_&quot; } { for (i = 1; i < NF; i ++) name = name &quot;_&quot; $i; print substr(name,2); name = &quot;&quot; }' inputfile

Bye!

KP.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top