gpt4 book ai didi

linux - 正则表达式 - 在第一次匹配后追加

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:51:59 25 4
gpt4 key购买 nike

假设我有以下类型的文件:

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 破折号(第一行带有 c c c)。

最佳答案

这个 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.
}

关于linux - 正则表达式 - 在第一次匹配后追加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28748698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com