我想在我的大文件中每隔30行插入一个字符串。我正在使用mini-sed,它不支持〜(代字号)范围运算符。我正在寻找仅限sed的解决方案。
答案 0 :(得分:43)
这个帖子是另一个如何使事情复杂化的例子。这应该这样做:
sed '0~30 s/$/string/g' < inputfile > outputfile
每行30行“string”插入到行尾。如果你想要一个带有“string”字样的新行,只需使用“\ n string”。
答案 1 :(得分:5)
每隔3行插入一行;
seq 1 10 | sed ': loop; n; n; a insert
n; b loop'
产
1
2
3
insert
4
5
6
insert
7
8
9
insert
10
相应地调整n;
命令之前a
命令的数量
答案 2 :(得分:2)
sed 'n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;s/$/\
string/' filename
答案 3 :(得分:2)
开始编辑
初始解决方案在保持空间中需要与N行的大小一样多的内存。这是一个更好的解决方案,只将'\n'
保留在保留空间而不是所有行,需要更少的内存:
sed -e 'p;G;s/[^\n]//g;t next;:next;s/^\n\{5\}$//;t insert;h;d;:insert;x;s/^.*$/new line/' your_large_file
使用比s命令更少知道的i命令可以完成同样的操作:
sed -e 'p;G;s/[^\n]//g;t next;:next;s/^\n\{5\}$//;t insert;h;d;:insert;x;i \
new line
d' your_large_file
同样,可以使用'sed -f script your_large_file'
:
# Whatever happen afterward, the current line need to be printed.
p
# Append the hold space, that contains as much \n as the number of lines read since the text has been added.
G
# Keeps only the \n in the pattern space.
s/[^\n]//g
# The 't next' bellow is needed so the 't insert' will not take into account the s command above.
t next
:next
# If we have exaclty 5 \n in the patern space, empty the hold space and insert the text, else save the pattern space for next cycle.
# In both cases, end the current cycle without printing the pattern space.
s/^\n\{3\}$//
t insert
h
d
:insert
x
i \
new line
d
结束修改
以下脚本将在每5行后添加'\nnew line'
。如果您想每6或100行执行此操作,只需按'\{5\}'
或'\{6\}'
更改'\{100\}'
。
sed -n -e 'H;g;s/[^\n]//g;t next;:next;s/^\n\{5\}$//;t insert;$ {x;s/^\n//;p};b;:insert;x;s/$/\nnew line/;s/^\n//;p' your_large_file
这值得一些解释,所以bellow是一个注释的脚本文件版本。它必须与'sed -n -f script your_large_file'
一起运行。
H
g
# Now, the pattern and hold space contain what has been read so far with an extra \n at the beginning.
s/[^\n]//g
# Now, the pattern space only contains \n, the hold space is unmodified.
# The 't next' bellow is needed so the 't insert' will not take into account the s command above.
t next
:next
# If we have exactly 5 new lines in the pattern space, the hold space is printed without the \n at the beginning and with the text to added after 5 lines at its end.
s/^\n\{5\}$//
t insert
# If not 5 \n and at the last line, the hold space must be printed without the \n at its beginning.
$ {x;s/^\n//;p}
b
:insert
x
# Now the hold space is empty and ready to receive new lines as the pattern space has been emptied by the 2 s commands above.
s/$/\nnew line/
s/^\n//
p
答案 4 :(得分:2)
使用
sed '1~30 i everyThirtyLine' file.dat
这是在Cygwin中测试的。
答案 5 :(得分:2)
这会在每3行后插入一行。
[STEP 101] # cat insert.sed
# add one more 'x' into the hold space
x
s/^/x/
t reset_t_cond
: reset_t_cond
# check if there are 3 'x' chars now
s/x\{3\}//
x
t insert
b
: insert
a\
INSERT HERE
[STEP 102] # seq 10 | sed -f insert.sed
1
2
3
INSERT HERE
4
5
6
INSERT HERE
7
8
9
INSERT HERE
10
[STEP 103] #