删除使用AWK尾随零 [英] remove trailing zero using awk

查看:87
本文介绍了删除使用AWK尾随零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的值在我的文件:

  1.5000
 0.006
 9.0001
 104.2500
 17.0000
 3.5000

我想删除尾随零,以下 AWK 将reove尾随零

 的awk'{如果($ 0〜/\\./){子(0 * $,,$ 0);子(\\\\ $,,$ 0);}}打印'文件

以上的awk输出,

  1.5
 0.006
 9.0001
 104.25
 17
 3.5

不过,我想补充一个零小数点后,即我想要的是一个浮点数没有尾随零值除外一样,2.0,3.0

的例外输出

  1.5
 0.006
 9.0001
 104.25
 17.0
 3.5


解决方案

使用 SED 可能是在这种情况下,简单的:

请注意:


  • 下使用 SED -E -r )启用的扩展的定期EX pressions,这使命令更可读的支持。它应该与GNU工作 SED (Linux)的和FreeBSD SED (OSX)。

  • 用单一的替换命令(取值/.../.../)。

  • 如果有输入整数,他们保持不变。

SED -ES / ^(* [0-9] + \\。[0-9]([0 -9] * [1-9])?)0 + $ / \\ 1 /'文件


  • ^ 开头和 $ 末确​​保的全部的输入行匹配

  • * 匹配前导空格,如果任何

  • [0-9] + \\。所有的数字相匹配的小数点前,加小数点

  • [0-9] 匹配的第一个小数位(个位数) - 这确保了数 .0 ,不会被剥离其尾部的 0

  • ([0-9] * [1-9])?任何附加数字匹配,直到一个的非零的遇到数字,如果有的话

  • 0 + 然后通过线的末端捕捉尾随零

  • 在替换字符串, \\ 1 指的 1 的捕捉组((...)),这是除了尾随零的一切 - 有效去除它们

  • 请注意,由于 SED 取值输出的默认行为的所有的线条 - 无论修改与否 - 行没有匹配的号码(数字,没吨需要修改)只是通过。

I have the following values in my file:

1.5000
 0.006
 9.0001
 104.2500
 17.0000
 3.5000

I want to remove the trailing zero, the following awk will reove the trailing zeros

awk '{ if ($0 ~ /\./){ sub("0*$","",$0); sub ("\\.$","",$0);} print}' file

Output of above awk,

1.5
 0.006
 9.0001
 104.25
 17
 3.5

But I want to add a single zero after the decimal point, I.e. All I want is a float number without trailing zero except values like, 2.0, 3.0

Excepted output

1.5
 0.006
 9.0001
 104.25
 17.0
 3.5

解决方案

Use of sed is probably simpler in this case:

Note:

  • The following uses sed with -E (alias of -r) to enable support for extended regular expressions, which makes the command more readable. It should work with GNU sed (Linux) and FreeBSD sed (OSX).
  • Uses a single substitution command (s/.../.../).
  • Should there be integers in the input, they are left untouched.

sed -E 's/^( *[0-9]+\.[0-9]([0-9]*[1-9])?)0+$/\1/' file

  • ^ at the beginning and $ at the end ensure that the entire input line is matched
  •  * matches leading spaces, if any
  • [0-9]+\. matches all digits before the decimal point, plus the decimal point
  • [0-9] matches the first decimal place (a single digit) - this ensures that a number ending in .0 isn't stripped of its trailing 0
  • ([0-9]*[1-9])? matches any additional digits until a nonzero digit is encountered, if any
  • 0+ then captures trailing zeros through the end of the line
  • in the replacement string, \1 refers to the 1st capture group ((...)), which is everything except the trailing zeros - effectively removing them.
  • Note that due to seds default behavior of outputting all lines - whether modified or not - lines without matching numbers (numbers that didn't need modification) are simply passed through.

这篇关于删除使用AWK尾随零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆