说我有以下类型的文件:
a a c
b b c
c c c
d d c
e e c
a a c
b b c
c c c
d d c
e e c
我最终如何:
a a c
b b c
c c c
—————
d d c
e e c
a a c
b b c
c c c
d d c
e e c
...而不只是在第3行(em dashes
的第一行)之后添加c c c
。
答案 0 :(得分:4)
这个awk会起作用:
awk '1; !flag && /c c c/ { flag = 1; print "—————" }' filename
那是:
1 # first, print every line (1 meaning true here, so the
# default action -- printing -- is performed on all
# lines)
!flag && /c c c/ { # if the flag is not yet set and the line we just printed
# matches the pattern:
flag = 1 # set the flag
print "—————" # print the dashes.
}
或者选择sed(虽然我建议使用awk解决方案):
sed -n 'p; /c c c/ { x; /^$/ { s//—————/; p }; x }' filename
这有点复杂。知道保持缓冲区在开头是空的:
p # print the line
/c c c/ { # if it matches the pattern:
x # exchange hold buffer and pattern space
/^$/ { # if the pattern space (that used to be the hold buffer) is
# empty:
s//—————/ # replace it with the dashes
p # print them
}
x # and exchange again. The hold buffer is now no longer empty,
# and the dash block will not be executed again.
}
答案 1 :(得分:1)
sed '/c c c/!b
s/$/\
-----/
# Using buffer
:cycle
N
$!b cycle' YourFile
c c c
,只需打印N
循环那样的动作)或通过使用小缓冲来替代大文件
# without big buffer
:cycle
n
s/.*\n//
$!b cycle' YourFile