我有一列如下:
ifile.txt
1.25
2.78
?
?
5.6
3.4
我想将浮点格式设置为十进制,并按原样跳过字符串。
ofile.txt
1
3
?
?
6
3
Walter A,F。Knorr和Janez Kuhar建议根据我的问题和需要的命令(例如,
awk '{printf "%d%s\n", $1}' ifile.txt
同样,我发现我有许多列,但是其他列不需要任何格式。所以我必须以类似以下形式使用上面的命令:
awk '{printf "%5s %d%s %5s %5s %5s\n", $1, $2, $3, $4, $5}' ifile.txt
例如:
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
我使用了F.Knorr再次建议的以下命令,
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
它工作正常,但需要对其进行格式化。喜欢
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
您可以先检查该列是否包含数字(通过正则表达式),然后相应地进行打印:
awk '$1~/^[0-9]+\.?[0-9]*$/{printf "%i\n",$1+0.5; next}1' test.txt
更新:如果是如上所述需要格式化的第n列(其他列中没有其他格式),请在以下命令中将其替换$1
为$n
:
awk '$1~/^[0-9]+\.?[0-9]*$/{$1=int($1+0.5)}1' test.txt
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句