If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Data Access, Manipulation & Batch Languages > Unix Shell Scripts > Unix - use of awk command

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 10-14-02, 21:17
ParulV ParulV is offline
Registered User
 
Join Date: Oct 2002
Posts: 74
Unix - use of awk command

Hi,

How can I get the value for Name and City for both records? Both records start with From: and end with [End Order]. There are blank lines between each field within a record. However, each record does not have the same number of fields (like first record does not have any City field and second record does). Therefore, I don't want to hard-code their positions ($1, $2, etc).

I was trying the following to get value for Name:
awk '{ print $2 }' RS="[End Order]" Sample.txt

Please help!

Thanks.
-Parul
parani19@hotmail.com

I have the following records in Sample.txt:
From:
Name: aaa

Street: bbb

[End Order]
From:
Name: ddd

Street: eee

City: fff

[End Order]
Reply With Quote
  #2 (permalink)  
Old 10-24-02, 07:11
Damian Ibbotson Damian Ibbotson is offline
Padawan
 
Join Date: Jun 2002
Location: UK
Posts: 525
You could do something like this (you get an additional record with a blank name and city at the end because you are using [End Order] as a row seperator)...

awk 'BEGIN {RS="[End Order]"} {
name=""; city=""
for (i=1; i<=NF; i++) {
if ($i=="Name:") {
name=$(i+1);
}
if ($i=="City:") {
city=$(i+1);
}
}
print NR,"Name =",name,"; City =",city;
}' << !!
From:
Name: aaa

Street: bbb

[End Order]
From:
Name: ddd

Street: eee

City: fff

[End Order]
!!
1 Name = aaa ; City =
2 Name = ddd ; City = fff
3 Name = ; City =
Reply With Quote
  #3 (permalink)  
Old 10-24-02, 09:25
Damian Ibbotson Damian Ibbotson is offline
Padawan
 
Join Date: Jun 2002
Location: UK
Posts: 525
Your names and cities will probably contain whitespace, so I'd suggest doing something like this instead...

awk 'BEGIN {FS=":"} {
if ($1=="Name") {
name=$2;
}
else if ($1=="City") {
city=$2;
}
else if ($1=="[End Order]") {
print ++counter, "Name = ", name, "; City = ", city;
name="";
city="";
}
else {
next;
}
}' << !!
From:
Name: Some Body

Street: Some Lane

[End Order]
From:
Name: Tiny Tom

Street: Some Road

City: A Big Town

[End Order]
!!
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On