how to keep initial spaces for 1st field with awk

ghz 8months ago ⋅ 142 views

I have a file of that type:

   aaaaaa bbbb     cccccc
     dddddddddddddd ee  fff
  gggggggg hhh   iiiii

I want to ouptut only 1st & 3rd fields, but keeping the original spaces of 1st field, like:

   aaaaaa cccccc
     dddddddddddddd fff
  gggggggg iiiii

if I use simple print($1,$3), I get:

aaaaaa cccccc
dddddddddddddd fff
gggggggg iiiii

I have tried adding: $1=sprintf("%20s",$1) --> but 1st field is aligned on its right side at the 20th column:

              aaaaaa cccccc
      dddddddddddddd fff
            gggggggg iiiii

thanks in advance for your (simple) proposal

PLP

i have tried using printf arguments, but I cannot output the exact number of spaces in front of 1st field

Answers

To achieve the desired output while maintaining the original spaces in the first field, you can use a combination of substr and printf to control the spacing. Here's how you can do it:

awk '{ printf "%s%s%s\n", substr($0, 1, index($0, $2)-1), $1, $3 }' filename

This awk command will:

  1. Use substr to extract the portion of the line before the start of the second field ($2).
  2. Print the first field ($1) without modifying it.
  3. Print the third field ($3).

This way, the original spaces in the first field will be preserved, and the output will have the desired format.