fembot
fembot

Reputation: 87

Using AWK to list several columns from a db queried list when some fields are blank?

I am trying to selectively display several columns from a db table(see sample below) using awk. While not all the fields are populated, I still need to return a blank field to represent it.

--------- -------------------------- ------------ ------
000       0000000000198012           702          29
000       0000000000198013                        29
000                                  702          29
000       0000000000198015           702          03
055       0000000000000001           702          

This is what I'm using:

select * from db| awk '{print $1,$3,$4}'

but in the rows where there is a blank field, awk is skipping over those fields and displaying the result from the next populated field. How do I display the results accurately?

-Thanks!

Upvotes: 2

Views: 352

Answers (2)

slitvinov
slitvinov

Reputation: 5768

gawk has FIELDWIDTHS
http://www.gnu.org/software/gawk/manual/html_node/Constant-Size.html
Usage:
command | awk -f foo.awk

foo.awk

NR==1 {
    for (i=1; i<=NF; i++) {
      FIELDWIDTHS = FIELDWIDTHS " " length($(i))+1
    }
}

NR>1 {
    print $1, $3, $4
}

Upvotes: 3

twalberg
twalberg

Reputation: 62379

If the columns have a consistent/static width, and the spacing is handled with ' ' characters, not tabs (meaning every line is the same length, regardless of missing fields), you could use cut with an appropriate list of field start/stop positions.

Upvotes: 2

Related Questions