Daniel
Daniel

Reputation: 1696

awk: delete the first column and add four columns after the last one

I have a file with data represented as:

32446191    0   5   5   2014-06-27  13210
62357877    18  89  89  2014-06-27  13210
33879626    81  1   1   2014-06-27  13210

Actually I have about 30 columns. I need to delete the first column (and the separator) and add four columns after the last one. Then the result would like:

0   5   5   2014-06-27  13210   0   0   0   0
18  89  89  2014-06-27  13210   0   0   0   0
81  1   1   2014-06-27  13210   0   0   0   0

How to do it in awk with one command? Appreciate for your help.

Upvotes: 0

Views: 83

Answers (4)

konsolebox
konsolebox

Reputation: 75488

Just print the columns with the extra 0's and use column -t:

awk '{ print $2, $3, $4, $5, $6, 0, 0, 0, 0 }' file | column -t

Output:

0   5   5   2014-06-27  13210  0  0  0  0
18  89  89  2014-06-27  13210  0  0  0  0
81  1   1   2014-06-27  13210  0  0  0  0

For custom columns:

awk -v columns='2 3 4 5 6' 'BEGIN { l = split(columns, c); } { t = $c[1]; for (i = 2; i <= l; ++i) t = t OFS $c[i]; print t, 0, 0, 0, 0; t = "" }' file

Modify OFS, use printf, or simply use column -t for the formatting.

Upvotes: 0

R Sahu
R Sahu

Reputation: 206577

awk '{for(i=2;i<=NF;++i) printf("%-4s ", $i); printf "  0  0  0  0\n"} file

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 203502

Preserving the original spacing:

$ awk -v OFS='   ' '{sub(/[^[:space:]]+[[:space:]]+/,""); print $0, 0, 0, 0, 0}' file
0   5   5   2014-06-27  13210   0   0   0   0
18  89  89  2014-06-27  13210   0   0   0   0
81  1   1   2014-06-27  13210   0   0   0   0

Tweak OFS to suit.

Upvotes: 1

ooga
ooga

Reputation: 15501

awk '{printf("%-4s%-4s%-4s%-12s%-5s  0  0  0  0\n",$2,$3,$4,$5,$6)}' file

Upvotes: 0

Related Questions