Results 1 to 3 of 3
  1. #1
    Join Date
    Oct 2002
    Posts
    74

    Unanswered: 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]

  2. #2
    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 =

  3. #3
    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]
    !!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •