简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM