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

sed用法举例(1)—行居中


有一个文本文件,每行(除去行首和行末的空白)的长度都不超过80个字符,例如 Vim 的帮助文档。现在想将此文件的每一行都居中显示,宽度为80个字符。可以用以下 sed 脚本实现。

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

# Put 80 spaces in the hold space
1 {
  x
  s/^$/          /
  s/^.*$/&&&&&&&&/
  x
}

# del leading and trailing spaces
y/\t/ /
s/^ *//
s/ *$//

# add a newline and 80 spaces to end of line
G

# keep first 81 chars (80 + a newline)
s/^\(.\{81\}\).*$/\1/

# \2 matches half of the spaces, which are moved to the beginning
s/^\(.*\)\n\(.*\)\2/\2\1/

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


相关文章


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

侧栏导航