Answers:
与awk
:
awk ' {print;} NR % 2 == 0 { print ""; }' inputfile
带sed
(GNU
扩展名):
sed '0~2 a\\' inputfile
与bash
:
#!/bin/bash
lines=0
while IFS= read -r line
do
printf '%s\n' "${line}"
((lines++ % 2)) && echo
done < "$1"
sed '0~2 a\ '
为每个插入的换行符添加了一个空格。如果你想在每一行后添加一个换行符,这些同样的工作:sed '0~1 a\ '
,sed 'a\ '
或只sed G
。
另一个awk味道:
awk '{ l=$0; getline; printf("%s\n%s\n\n", l, $0) }'
与(GNU)sed
:
sed '0~2G'
简短(N = 100时很丑):
sed 'n;G'
man sed解释〜为:
第一〜步
匹配每一个step'th线与第一行开始。例如,``sed -n 1〜2p''将打印输入流中的所有奇数行,并且地址2〜5将匹配从第五行开始的第二行。首先可以为零;在这种情况下,sed的运行就好像与step相同。(这是一个扩展。)
与其他sed(计算新行):
sed -e 'p;s/.*//;H;x;/\n\{2\}/{g;p};x;d'
或者,为了更便于移植,写为(删除某些版本的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.
使用awk
,可能是:
awk '1 ; NR%2==0 {printf"\n"} '
[[ ]]
测试:while read line; do echo "$line"; ((lines++ % 2)) && echo; done
。