幽谷奇峰 | 燕雀鸣幽谷,鸿鹄掠奇峰

sed用法举例(2)—非负整数加一


众所周知,对非负整数加一,就是让个位数加一,即用个位数的下一个数字来取代它。唯一的例外就是,当个位数为9时,加一后变为0,而它的前一个数位上的数字也得加一,依次类推。

以下脚本就利用 sed 命令实现了对非负整数加一的操作。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/bin/sed -f

/[^0-9]/ d

# replace all trailing 9 by _ (any other character except digits, could
# be used)
:d
s/9\(_*\)$/_\1/
td

# increase last digit only.  The first line adds a most-significant
# digit of 1 if we have to add a digit.
#
# The `tn' commands are not necessary, but make the thing
# faster

s/^\(_*\)$/1\1/; tn
s/8\(_*\)$/9\1/; tn
s/7\(_*\)$/8\1/; tn
s/6\(_*\)$/7\1/; tn
s/5\(_*\)$/6\1/; tn
s/4\(_*\)$/5\1/; tn
s/3\(_*\)$/4\1/; tn
s/2\(_*\)$/3\1/; tn
s/1\(_*\)$/2\1/; tn
s/0\(_*\)$/1\1/; tn

:n
y/_/0/

此脚本首先忽略掉包含非数字字符的行,然后把数字末尾的9全部替换成下划线,再通过一系列的替换命令对数字进行加一,最后,把结果中的下划线替换成0.


本作品由 Yysfire 创作,采用知识共享许可协议进行许可。转载时请在显著位置标明本文永久链接:
http://yysfire.github.io/linux/sed-example-non-negative-integer-plus-one.html


相关文章


最后修改
2012-10-25 18:16
发表时间
2012-10-25 18:13
本文标签
Linux 18 Regexp 3 sed 3
关注我

侧栏导航