user3657270
user3657270

Reputation: 43

Gawk / If / Printf / Print everything in columns

Could somebody tell me how I solve this problem :

plym    fury    1970    73  2500
chevy   malibu  1999    60  3000
ford    mustang 1965    45  10000
volvo   s80     1998    102 9850
ford    thundbd 2003    15  10500
chevy   malibu  2000    50  3500
bmw     325i    1985    115 450
honda   accord  2001    30  6000
ford    taurus  2004    10  17000
toyota  rav4    2002    180 750
chevy   impala  1985    85  1550
ford    explor  2003    25  9500

Command :

gawk '{if ($1=="plym")($1="plymouth")};{print}' cars

Result :

plymouth fury 1970 73 2500
chevy   malibu  1999    60  3000
ford    mustang 1965    45  10000
volvo   s80     1998    102 9850
ford    thundbd 2003    15  10500
chevy   malibu  2000    50  3500
bmw     325i    1985    115 450
honda   accord  2001    30  6000
ford    taurus  2004    10  17000
toyota  rav4    2002    180 750
chevy   impala  1985    85  1550
ford    explor  2003    25  9500

I want the line of plymouth to be on the same column like the rest of the details

Upvotes: 1

Views: 150

Answers (2)

Jotne
Jotne

Reputation: 41460

To preserve tab format of line use sub in awk

awk '{sub(/plym/,"&outh")}1' file | column -t
plymouth  fury     1970  73   2500
chevy     malibu   1999  60   3000
ford      mustang  1965  45   10000
volvo     s80      1998  102  9850
ford      thundbd  2003  15   10500
chevy     malibu   2000  50   3500
bmw       325i     1985  115  450
honda     accord   2001  30   6000
ford      taurus   2004  10   17000
toyota    rav4     2002  180  750
chevy     impala   1985  85   1550
ford      explor   2003  25   9500

Upvotes: 0

Yirkha
Yirkha

Reputation: 13848

When parsing the line, Awk ignores all separators (as set in variable FS).

If you change any field, Awk recreates the line into $0 (implicit in your call to print() without arguments) by splicing the fields (columns) with OFS instead, which is just a single space character by default.

You might try to set OFS to a tab character like so:

BEGIN { OFS = "\t" }

If you are lucky and no identifiers are longer than 7 characters (which seems to be true in the original file), it could work.

But if you require special column width, e.g. because "plymouth" is longer now, you will need to use printf() instead, e.g.:

{ printf("%-10s %-7s %-7s %-3s %s\n", $1, $2, $3, $4, $5) }

For more information, see your man awk or some web variant of it.

Upvotes: 1

Related Questions