【问题标题】:regex - append after first match正则表达式 - 在第一次匹配后追加
【发布时间】:2015-04-29 04:46:08
【问题描述】:

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

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

...不只是在第三行之后添加em dashes(第一行是c c c)。

【问题讨论】:

  • 你到底是什么意思?仅在第一次出现 c c c 之后插入破折号而不是后续的?

标签: linux awk sed text-processing


【解决方案1】:

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

【讨论】:

  • 可能只有GNU sed,但这应该也可以sed '0,/c c c/s//&\n-----/' file。 ++ 仍然如此。
  • @jaypalsingh 它确实有效。你想单独回答,还是我应该接受 Wintermute 的?
  • @jaypalsingh:啊,一个警告:它只有在 c c c 位于匹配行的末尾时才有效。这不是线条模式的问题(即^c c c$),但如果模式应该只匹配线条的一部分并且仍然应该在线条之后插入破折号,您将需要sed '0,/c c c/ { // s/.*/&\n-----/ }' 左右。尽管如此,范围的想法还是不错的。
  • @Det 请继续接受这个答案。 Wintermute,真的。
【解决方案2】:
sed '/c c c/!b
s/$/\
-----/
# Using buffer
:cycle
N
$!b cycle' YourFile
  • 直到第一个c c c,只打印该行
  • 在线添加一行(所以在第一个 ccc)
  • 在缓冲区中加载一行(不打印)
  • 循环加载直到最后一行
  • 最后一行打印整个内容(通过退出循环,而不是像新的N 循环那样的操作)

或使用小缓冲替代大文件

# without big buffer
:cycle
n
s/.*\n//
$!b cycle' YourFile
  • 打印第一行并加载新行
  • 删除第一行
  • 如果不是结束就循环

【讨论】:

    猜你喜欢
    • 2022-01-11
    • 1970-01-01
    • 2015-04-29
    • 2016-03-18
    • 1970-01-01
    • 2014-12-04
    • 2013-09-30
    • 1970-01-01
    相关资源
    最近更新 更多