Sed - 增加大于x的所有值

时间:2015-03-24 09:51:00

标签: sed

我希望从特定快照开始增加所有快照的快照编号(使用sed)。如何从快照= 22开始增加快照编号?

// 我已经找到了增加整个快照编号的命令 sed -r 's/(snapshot=)([0-9]+)/echo \1$((\2+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

1 个答案:

答案 0 :(得分:2)

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

然而,使用awk非常简单:

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

这可以通过将行拆分为=个分隔符的字段,然后:

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

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

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