Sed - 递增所有大于 x 的值

Sed - increment all values greater than x

我想增加从某个快照开始的所有快照的快照编号(通过使用 sed)。如何增加快照编号,例如从快照=22 开始?

// 我已经找到了增加整个快照编号的命令 sed -r 's/(snapshot=)([0-9]+)/echo $((+1))/ge' myInputFile

我有这样的文件:

#-----------
snapshot=4
#-----------
time=1449929
mem_heap_B=110
mem_heap_extra_B=40
mem_stacks_B=0
heap_tree=peak
#-----------
snapshot=5
#-----------
time=1449929
mem_heap_B=110
mem_heap_extra_B=40
mem_stacks_B=0
heap_tree=peak
.
.
.
#-----------
snapshot=22
#-----------
time=1448920
mem_heap_B=10
mem_heap_extra_B=24
mem_stacks_B=0
heap_tree=detailed
.
.
.
#-----------
snapshot=46
#-----------
time=1449964
mem_heap_B=110
mem_heap_extra_B=24
mem_stacks_B=0
heap_tree=detailed
.
.
.
#-----------
snapshot=172
#-----------
time=1448920
mem_heap_B=10

我想要得到以下输出:

#-----------
snapshot=4
#-----------
time=1449929
mem_heap_B=110
mem_heap_extra_B=40
mem_stacks_B=0
heap_tree=peak
#-----------
snapshot=5
#-----------
time=1449929
mem_heap_B=110
mem_heap_extra_B=40
mem_stacks_B=0
heap_tree=peak
.
.
.
#-----------
snapshot=23
#-----------
time=1448920
mem_heap_B=10
mem_heap_extra_B=24
mem_stacks_B=0
heap_tree=detailed
.
.
.
#-----------
snapshot=47
#-----------
time=1449964
mem_heap_B=110
mem_heap_extra_B=24
mem_stacks_B=0
heap_tree=detailed
.
.
.
#-----------
snapshot=173
#-----------
time=1448920
mem_heap_B=10

您会发现使用 sed 很难做到这一点,因为 sed 没有内置的算术功能(并且在纯 sed 中实现它不是一个明智的想法)。

不过用awk就很简单了:

awk -F = 'BEGIN { OFS = FS }  == "snapshot" &&  >= 22 { ++ } 1' filename

这通过将行拆分为 = 分隔符的字段来实现,然后:

BEGIN {
  OFS = FS                      # use the same separator in the output
}                               # as for the input

 == "snapshot" &&  >= 22 {  # if the first field in a line is "snapshot"
                                # and the second larger than or equal to 22:

  ++                          # increment the second field
}
1                               # print the resulting line (unchanged if the
                                # condition was not met)