Kay
Kay

Reputation: 2077

how to format simultaneously a string and floating number in awk?

I have a column as follows:

ifile.txt
1.25
2.78
?
?
5.6
3.4

I would like to format the floating points to decimal and skipping the strings as it is.

ofile.txt
1
3
?
?
6
3

Walter A, F. Knorr and Janez Kuhar suggested nice scripts to do it as per my question and need of a command like

awk '{printf "%d%s\n", $1}' ifile.txt

Again, I found I have a number of columns, however, other columns don't need any formatting. So I have to use the above command in the form of something like:

awk '{printf "%5s %d%s %5s %5s %5s\n", $1, $2, $3, $4, $5}' ifile.txt

for example:

ifile.txt
1  1.25   23.2    34  3.4
2  2.78   22.0    23  1.2
3     ?      ?     ?  4.3
4     ?      ?     ?  6.5
5   5.6   45.0     5  2.4
6   3.4   43.0    23  5.6

I used the following command as again suggested by F. Knorr in answer,

awk '$2~/^[0-9]+\.?[0-9]*$/{$2=int($2+0.5)}1' ifile.txt > ofile.txt

ofile.txt
1  1 23.2    34  3.4
2  3 22.0    23  1.2
3  ?      ?     ?  4.3
4  ?      ?     ?  6.5
5  6 45.0     5  2.4
6  3 43.0    23  5.6

It works fine, but need to format it. like

ofile.txt
1  1   23.2    34  3.4
2  3   22.0    23  1.2
3  ?      ?     ?  4.3
4  ?      ?     ?  6.5
5  6   45.0     5  2.4
6  3   43.0    23  5.6

Upvotes: 1

Views: 574

Answers (2)

F. Knorr
F. Knorr

Reputation: 3055

You could first check whether the column contains a number (via regex) and then handle the printing accordingly:

 awk '$1~/^[0-9]+\.?[0-9]*$/{printf "%i\n",$1+0.5; next}1' test.txt

Update: If it is the n-th column that needs to be formatted as described above (and no other formatting in other columns), then replace all $1 by $n in the following command:

awk '$1~/^[0-9]+\.?[0-9]*$/{$1=int($1+0.5)}1' test.txt

Upvotes: 5

Walter A
Walter A

Reputation: 20002

Just adding a half can be done with:

awk ' $1 ~ /^[0-9]+$|^[0-9]+.[0-9]+$/ { printf("%d\n", $1 + 0.5); next }
      { print $1 } ' file

or slightly shorter:

awk ' $1 ~ /^[0-9]+$|^[0-9]+.[0-9]+$/ { printf("%d\n", $1 + 0.5); next } 1' file

Upvotes: 1

Related Questions