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

to search for a number in the first column and change the value in second column depending on its value in linux

我有如下输入

$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

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

提前致谢

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

With -v needle=14725 needle 在 awk 代码中的值将是 14725一个变量),然后

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

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

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

就地编辑文件。

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

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

主要的变化是,我们使用 sub(/[^[:space:]]*$/, "0.0020000e+00");,而不是 = 0.002,这会导致从字段重建行,它替换了最后一批非 space 字符符合 "0.0020000e+00"。而且,为了避免搞砸,我们检查该字段中是否只有两条线。