3

I am looking to parse a space delimited input text file using awk. The column code can have more than one row for each group. I would greatly appreciate any help with this.

LOCATION
SHANNON

GROUP  NUM  SWITCH  CODE HEX
0      4     OFF    1    3
1      13    ON     2    4      
                    8
                    14

LOCATION
LOUTH

GROUP  NUM  SWITCH  CODE HEX 
0      1    OFF     1    4
1      2    ON      0    F
                    2

Desired output file

LOCATION GROUP  NUM  SWITCH  CODE HEX
SHANNON   0     4    OFF     1    3
SHANNON   1     13   ON      2    4  
SHANNON   1     13   ON      8    4  
SHANNON   1     13   ON      14   4 
LOUTH     0     1    OFF     1    4
LOUTH     1     2    ON      0    F
LOUTH     1     2    ON      2    F
6
  • why does it have to be awk? Commented Sep 17, 2013 at 14:47
  • awk seems to be very quick and does not use any other programs Commented Sep 17, 2013 at 14:48
  • I was using vba for parsing, in comparison awk is much quicker in performing similar operations. Do you have any other way to suggest? Commented Sep 17, 2013 at 15:04
  • 1
    Awk is powerful but has limits though and when it tries to comprehend for its limits, that would be the point where it becomes slow or code bulky. Commented Sep 17, 2013 at 15:15
  • @SantoshPillai When other variables are not present, it's only the code that code exist right? Commented Sep 17, 2013 at 15:17

1 Answer 1

5
#!/usr/bin/awk -f

BEGIN {
    # You can customize this to change your output layout based on your preference.
    format = "%-10s%-7s%-5s%-8s%-5s%-3s\n"
    printf format, "LOCATION", "GROUP", "NUM", "SWITCH", "CODE", "HEX"
}
++i==2{
    l = $1
}
i>4{
    if (/^[[:blank:]]*$/) {
        i = 0
    } else if (NF > 1) {
        printf format, l, $1, $2, $3, $4, $5
        p1=$1; p2=$2; p3=$3; p5=$5
    } else {

        printf format, l, p1, p2, p3, $1, p5
    }
}

Run with:

awk -f script.awk file

Output:

LOCATION  GROUP  NUM  SWITCH  CODE HEX
SHANNON   0      4    OFF     1    3  
SHANNON   1      13   ON      2    4  
SHANNON   1      13   ON      8    4  
SHANNON   1      13   ON      14   4  
LOUTH     0      1    OFF     1    4  
LOUTH     1      2    ON      0    F  
LOUTH     1      2    ON      2    F  
Sign up to request clarification or add additional context in comments.

2 Comments

@SantoshPillai Please check.
Works great. Perfect :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.