[ Home  |  FAQ-Related Q&As  |  General Q&As  |  Answered Questions ]


    Search the Q&A Archives


I have multiple line 6 column data, but some lines have the...

<< Back to: comp.lang.awk FAQ

Question by tom
Submitted on 4/25/2004
Related FAQ: comp.lang.awk FAQ
Rating: Not yet rated Rate this question: Vote
I have multiple line 6 column data, but some lines have the first two columns empty. What I want to do is have awk do:
1. Save the first field of the very first line
2. If the first field of a line is empty, use the first field of the previous line.
3. If a new line has a non-empty first field, then just print the line but save the first field to use if the next line has an empty first field and so on.

The program which generates the data omits the first two fields if they would be the same as those above and it is causing me a lot of hassle as I need that data to carry out searches for specific lines.

Any help would be greatly appreciated!


Answer by Gus
Submitted on 8/24/2004
Rating: Not yet rated Rate this answer: Vote
If you have exactly six fields, and awk splits these fields appropriately (e.g. no spaces within any of your field values, or you have a delimiter you put in the -F option), then this should work:

(NF==6) {
  first=$1
  second=$2
  print
}
(NF==5) {
  second=$1
  print first, $0
}
(NF==4) {
  print first, second, $0
}

In a more general case (another number of columns, more possible empty fields), I would probably keep an array variable  of the whole thing, resulting in something like:

BEGIN {
  maxf=6 # override with -v maxf=n on cmd line
}
{
for (i=1; i<=NF ; i++)
    field[maxf+i-NF]=$(i)
for (i=1; i<=maxf; i++)
    printf " %s", field[i]
printf "\n"
}

 

Your answer will be published for anyone to see and rate.  Your answer will not be displayed immediately.  If you'd like to get expert points and benefit from positive ratings, please create a new account or login into an existing account below.


Your name or nickname:
If you'd like to create a new account or access your existing account, put in your password here:
Your answer:

FAQS.ORG reserves the right to edit your answer as to improve its clarity.  By submitting your answer you authorize FAQS.ORG to publish your answer on the WWW without any restrictions. You agree to hold harmless and indemnify FAQS.ORG against any claims, costs, or damages resulting from publishing your answer.

 

FAQS.ORG makes no guarantees as to the accuracy of the posts. Each post is the personal opinion of the poster. These posts are not intended to substitute for medical, tax, legal, investment, accounting, or other professional advice. FAQS.ORG does not endorse any opinion or any product or service mentioned mentioned in these posts.

 

<< Back to: comp.lang.awk FAQ


[ Home  |  FAQ-Related Q&As  |  General Q&As  |  Answered Questions ]

© 2008 FAQS.ORG. All rights reserved.