0

I have a file with 7 columns and I want to get the first 4 and format them with awk. When I use awk without formatting it works however when I put it with printf it happens that the first character of the first line goes to the last line.

Example when I use sed -n "323,384p" file.xyz | awk '{print $1, $2, $3, $4}'

H 1.159798 1.491313 -0.946869
O 0.854926 2.591706 0.311355
O 1.225042 0.465961 2.017823
O 3.035434 -1.589327 2.087115
H 2.323008 -0.909968 6.144897
H 0.166459 -2.029119 3.043016
H 1.551022 -2.693028 4.563796
H 0.353505 -2.316287 5.790394

However, when I use sed -n "323,384p" file.xyz | awk '{printf "%15s %15s %15s \n" $1, $2, $3, $4}'

       1.159798        1.491313       -0.946869  
H       0.854926        2.591706        0.311355  
O       1.225042        0.465961        2.017823  
O       3.035434       -1.589327        2.087115  
O       0.588302       -2.894040        1.612656  
O       2.323008       -0.909968        6.144897  
H       0.166459       -2.029119        3.043016  
H       1.551022       -2.693028        4.563796  
H       0.353505       -2.316287        5.790394  
H

The letter H that should appear first for some reason goes on a new line after the last line. Would anyone please know how to fix this problem?

For simplicity's sake I didn't put all lines from the xyz file

2
  • You have three format specifiers in your printf but four arguments. Try correcting that and report back the results. You also have two single quotes at the end of the command line - is this a typo?
    – doneal24
    Jan 22 at 20:30
  • @doneal24 in the first command there was a typo already fixed. If I put another %15s for the fourth argument I get an error: awk: cmd. line:1: (FILENAME=- FNR=1) fatal: not enough arguments to satisfy format string %15s %15s %15s %15s H' ^ ran out for this one` Jan 22 at 20:55

1 Answer 1

0

There are three placeholders in the printf statement. $1 is appended to the format string after the newline since there is no comma before $1. Fields $2, $3 and $4 are formatted with printf. The result is that $1 is always printed after the newline.

You probably want to format all four fields with printf:

... | awk '{printf "%s %15s %15s %15s\n", $1, $2, $3, $4}'
2
  • Thank you @Freddy, but when I try this sed -n "323,384p" file.xyz | awk '{printf "%s %15s %15s %15s\n" $1, $2, $3, $4}' I have a error: awk: cmd. line:1: (FILENAME=- FNR=1) fatal: not enough arguments to satisfy format string %s %15s %15s %15s H' ^ ran out for this one` Jan 22 at 21:05
  • 1
    Add a comma before $1.
    – Freddy
    Jan 22 at 21:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .