每隔N行插入一行吗?


24

如何使用文本处理工具在每N行之后插入新行?

N = 2的示例:

输入:

sadf
asdf
yxcv
cxv
eqrt
asdf

输出:

sadf
asdf

yxcv
cxv

eqrt
asdf

Answers:


28

awk

awk ' {print;} NR % 2 == 0 { print ""; }' inputfile

sedGNU扩展名):

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"

2
算术评估可以直接作为条件,没有必要的[[ ]]测试:while read line; do echo "$line"; ((lines++ % 2)) && echo; done
manatwork 2011年

1
请注意,上面记录的命令sed '0~2 a\ '为每个插入的换行符添加了一个空格。如果你想在每一行后添加一个换行符,这些同样的工作:sed '0~1 a\ 'sed 'a\ '或只sed G
Acumenus


4
sed n\;G <infile

... 是你所需要的全部 ...

例如:

seq 6 | sed n\;G

输出:

1
2

3
4

5
6

... (第6个空格后面也有空格) ...或...

seq 5 | sed n\;G

输出:

1
2

3
4

5

(5后面没有空格)

如果在最后一行情况下始终应省略空格:

sed 'n;$!G' <infile


1

sed(GNU)

与(GNU)sed

sed '0~2G'

简短(N = 100时很丑):

sed 'n;G'

man sed解释〜为:

第一〜步
匹配每一个step'th线与第一行开始。例如,``sed -n 1〜2p''将打印输入流中的所有奇数行,并且地址2〜5将匹配从第五行开始的第二行。首先可以为零;在这种情况下,sed的运行就好像与step相同。(这是一个扩展。)

sed(其他)

与其他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,可能是:

awk '1 ; NR%2==0 {printf"\n"} '
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.