linux - 搜索第一列中的数字并根据其在 Linux 中的值更改第二列中的值

标签 linux awk sed

我有如下输入

$Interpreted from averaged nodal data
14725   0.0000000e+00
14726   0.0000000e+00
14727   0.0000000e+00
16263   6.4771147e-03
16264   6.3834046e-03
16265   6.4125084e-03
16266   6.5514743e-03

中间有时也会出现文本,但当一行有数字时,它仍然如上所示

我必须在第一个位置搜索某个数字,然后检查第二个数字。如果第二个数字大于某个值(例如 0.002),则可以保持这样,但如果它小于 0.002,则该值在同一文件中更改为 0.002。就像如果我想搜索 14725 并且它的值为零文件应该转向

$Interpreted from averaged nodal data
14725   0.0020000e+00
14726   0.0000000e+00
14727   0.0000000e+00
16263   6.4771147e-03
16264   6.3834046e-03
16265   6.4125084e-03
16266   6.5514743e-03

所有数据都是空格分隔的,在左边的数字之前,我们也有空格。左侧始终保持整数,而右侧始终为实数。 对 awk 或 sed -i 对于 infile 更改有什么建议吗?

提前致谢

最佳答案

awk -v needle=14725 '$1 == needle && $2 < 0.002 { $2 = 0.002 } 1' filename

使用 awk 代码中的 -v Needle=14725 needle 将具有值 14725 (使用固定值,您可以将其直接放入代码中,但我假设它来自变量),然后

$1 == needle && $2 < 0.002 {   # if the first field is the searched number
                               # and the second smaller than 0.002
  $2 = 0.002                   # set the second field to 0.002.
                               # Use $2 = "0.0020000e+00" if the
                               # number format is important.
}
1                              # print.

使用 GNU awk 4.1.0 或更高版本,您可以使用

awk -i inplace -v needle=14725 '$1 == needle && $2 < 0.002 { $2 = 0.002 } 1' filename

就地编辑文件。

附录(评论答案):为了保持格式完整,我会使用

awk -v needle=14727 '$1 == needle && NF == 2 && $2 < 0.002 { sub(/[^[:space:]]*$/, "0.0020000e+00"); } 1' filename

主要的变化是,我们使用 sub(/[^[:space:]]*$/, "0.0020000e+00");,而不是导致从字段重建行的 $2 = 0.002,它将行中最后一批非空格字符替换为 “0.0020000e+00”。而且,为了避免出现问题,我们检查该字段中是否只有两行。

关于linux - 搜索第一列中的数字并根据其在 Linux 中的值更改第二列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28903753/

相关文章:

MySQL 无法启动 - 错误 : su: warning: cannot change directory to/nonexistent: No such file or directory

linux - 在 CentOS 上永久安全地删除文件

Apache2 下的 PHP5-ldap 和 LDAPS(不工作)与 CLI(工作)

bash - 如何清理 masscan 输出 (-oL)

shell - 使用 awk 或 sed 将十六进制转换为十进制

bash - bash中除第一个单词外的字符串的相反顺序

linux - 在不重启 Ubuntu 的情况下全局设置环境变量

bash - 删除除最后一行以外的所有以相同字符串开头的行

linux - awk 留空行

linux - 将 awk,sed 输出设置为 Bash 中的变量