我想在文档的每四行添加一个新行。
例如:
abc
def
ghi
jkl
mno
pqr
stu
vw
xyz
Run Code Online (Sandbox Code Playgroud)
应该变成:
abc
def
ghi
jkl
mno
pqr
stu
vw
xyz
Run Code Online (Sandbox Code Playgroud)
ImH*_*ere 12
sed '0~4G'
Run Code Online (Sandbox Code Playgroud)
man sed 将 ~ 解释为:
first ~ step
匹配从 line first 开始的每 step'th 行。例如,``sed -n 1~2p'' 将打印输入流中的所有奇数行,地址 2~5 将匹配每第五行,从第二行开始。第一个可以为零;在这种情况下,sed 的操作就好像它等于 step。(这是一个扩展。)
简短(丑陋的 100 行):
sed 'n;n;n;G'
Run Code Online (Sandbox Code Playgroud)
或者,计算新行:
sed -e 'p;s/.*//;H;x;/\n\{4\}/{g;p};x;d'
Run Code Online (Sandbox Code Playgroud)
或者,为了更便携,写为(删除某些版本的 sed 的注释):
sed -e ' # Start a sed script.
p # Whatever happens later, print the line.
s/.*// # Clean the pattern space.
H # Add **one** newline to hold space.
x # Get the hold space to examine it, now is empty.
/\n\{4\}/{ # Test if there are 4 new lines counted.
g # Erase the newline count.
p # Print an additional new line.
} # End the test.
x # match the `x` done above.
d # don't print anything else. Re-start.
' # End sed script.
Run Code Online (Sandbox Code Playgroud)
大概:
awk '1 ; NR % 4 == 0 {printf"\n"} '
Run Code Online (Sandbox Code Playgroud)