Reorder of fields

I need to reorder the fields of an input file. I was using the following awk statement but I am stumped on how to get it exactly as I need.

I need the output to be tab delimited except for the CITY, NAME and ID. Those last set of columns should be a single field separated by a space. And they are variable in length, ie, can be 1 or 5+ columns in length.

So basically fields 1-7 and the last 2 fields put in their proper positions tab delimited, then put everything else in the last field space delimited.

awk '{ print $1,$8,$2,$(NF-1),$(NF),$3,$4,$5$6$7,$1="",$2="",$3="",$4="",$5="",$6="",$7="",$8="",$0 }'

Input

500 XYZ3849 2 30 1964 09 17 ST CITY NAME AP ID 37 -84
500 XYZ3850 3 40 1998 10 27 ST CITY NAME AP 37 -84
500 XYZ3851 4 50 2013 05 7 ST CITY NAME 37 -84

Needed Output

500    ST    XYZ3849    37    -84    2    30    19640917    CITY NAME AP ID
500    ST    XYZ3850    37    -84    3    40    19981027    CITY NAME AP 
500    ST    XYZ3851    37    -84    4    50    20130507    CITY NAME 

Any help is appreciated.

Thanks!

Where is the "KY" coming from?

You can "cheat" by pasting together multiple separators without commas. They'll be concatenated instead of separated by OFS.

awk -v OFS="\t" '{ print "tab", "separated", "space separated " $1 " " $2 " " $3 }' input 

I don't know why you're printing all the $8="" and things. If you just leave them out, they won't be printed at all, you don't need to unset them.

$0 is a special variable meaning 'entire line'. Not sure why that's in there either.

Oversight that has since been corrected.

awk -v OFS="\t" '{
        S=""
        for(N=9; N<=(NF-2); N++) S = S " " $N # Paste fields 9 - (NF-2)
        print $1, $8, $2, $(NF-1), $NF, $3, $4, $5 $6 $7, substr(S,2);
}' spacesep

for 2 digits $6 $7:

print $1, $8, $2, $(NF-1), $NF, $3, $4, $5 sprintf("%02d%02d",$6,$7), substr(S,2);

Thanks to both of you.

I incorporated both your suggestions and had to create a tab separation between

37 -84

This is what I think will work for the long term.

awk -v OFS="\t" '{
        S=""
        for(N=9; N<=(NF-2); N++) S = S " " $N # Paste fields 9 - (NF-2)
        print $1, $8, $2, $(NF-1),"\t"$NF, $3, $4, $5 sprintf("%02d%02d",$6,$7), substr(S,2);
}'
1 Like