EA00
EA00

Reputation: 633

Awk - Adding specific number of spaces between columns

My input file has columns which are space evenly like so:

X a b C D

How do I use awk to specify the number of spaces between the columns such that I get something like this:

X     a b    C         D

I know how to count the spaces between the columns using awk, I just don't know how to add those spaces in order to get the layout I want. Any suggestions?

Upvotes: 1

Views: 677

Answers (2)

karakfa
karakfa

Reputation: 67467

with awk

$ echo "X a b C D" | awk '{printf "%-6s%-2s%-5s%-9s%s\n", $1,$2,$3,$4,$5}'

X     a b    C        D

or with printf directly

$ echo "X a b C D" | xargs printf "%-6s%-2s%-5s%-9s%s\n"
X     a b    C        D

Upvotes: 5

glenn jackman
glenn jackman

Reputation: 246744

This is where printf comes in handy:

$ echo "X a b C D" | perl -lane 'printf "%-6s%-2s%-5s%-9s%s\n", @F'
X     a b    C        D

Adjust the field widths as required.

Upvotes: 1

Related Questions