如何使用文本处理工具在每 N 行后插入一个新行?
N=2 的示例:
输入:
sadf
asdf
yxcv
cxv
eqrt
asdf
Run Code Online (Sandbox Code Playgroud)
输出:
sadf
asdf
yxcv
cxv
eqrt
asdf
Run Code Online (Sandbox Code Playgroud)
Pri*_*ley 40
与awk
:
awk ' {print;} NR % 2 == 0 { print ""; }' inputfile
Run Code Online (Sandbox Code Playgroud)
与sed
(GNU
扩展名):
sed '0~2 a\\' inputfile
Run Code Online (Sandbox Code Playgroud)
与bash
:
#!/bin/bash
lines=0
while IFS= read -r line
do
printf '%s\n' "${line}"
((lines++ % 2)) && echo
done < "$1"
Run Code Online (Sandbox Code Playgroud)
sed n\;G <infile
Run Code Online (Sandbox Code Playgroud)
... 是你所需要的全部 ...
例如:
seq 6 | sed n\;G
Run Code Online (Sandbox Code Playgroud)
1
2
3
4
5
6
Run Code Online (Sandbox Code Playgroud)
... (6 后面也有一个空格) ...或者...
seq 5 | sed n\;G
Run Code Online (Sandbox Code Playgroud)
1
2
3
4
5
Run Code Online (Sandbox Code Playgroud)
(5后面没有空格)
如果在最后一行情况下应始终省略空格:
sed 'n;$!G' <infile
Run Code Online (Sandbox Code Playgroud)
与(GNU)sed
:
sed '0~2G'
Run Code Online (Sandbox Code Playgroud)
简短(丑陋的 N=100):
sed 'n;G'
Run Code Online (Sandbox Code Playgroud)
man sed 将 ~ 解释为:
first ~ step
匹配从 line first 开始的每 step'th 行。例如,``sed -n 1~2p'' 将打印输入流中的所有奇数行,地址 2~5 将匹配每第五行,从第二行开始。第一个可以为零;在这种情况下,sed 的操作就好像它等于 step。(这是一个扩展。)
与其他 sed (计算新行):
sed -e 'p;s/.*//;H;x;/\n\{2\}/{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\{2\}/{ # Test if there are 2 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
,大概是:
awk '1 ; NR%2==0 {printf"\n"} '
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
51752 次 |
最近记录: |