带有字符串的 awk 段落和 pgn 国际象棋游戏中的以下段落

带有字符串的 awk 段落和 pgn 国际象棋游戏中的以下段落

如何使用 awk 获取包含字符串的段落和后面的段落?

该文件如下所示:

[Event "Chess game"]
[Date "2021.01.08"]
[White "Player A"]
[Black "Player B"]
[Result "0-1"]

1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Bc5 5. O-O b5 6. Bb3 Nf6
7. Nxe5 Nxe5 8. d4 Ba7 9. dxe5 Ng8 10. Qd5 0-1

[Event "Chess game"]
[Date "2021.01.08"]
[White "Player B"]
[Black "Player C"]
[Result "0-1"]

1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Bc5 5. O-O b5 6. Bb3 Nf6
7. Nxe5 Nxe5 8. d4 Ba7 9. dxe5 Ng8 10. Qd5 0-1

[Event "Chess game"]
[Date "2021.01.08"]
[White "Player C"]
[Black "Player A"]
[Result "0-1"]

1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Bc5 5. O-O b5 6. Bb3 Nf6
7. Nxe5 Nxe5 8. d4 Ba7 9. dxe5 Ng8 10. Qd5 0-1

该命令返回我想要的段落:

> awk '/Player A/' RS="\n\n" ORS="\n\n" file.pgn

如何在游戏动作中添加以下段落?

像这样:

[Event "Chess game"]
[Date "2021.01.08"]
[White "Player A"]
[Black "Player B"]
[Result "0-1"]

1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Bc5 5. O-O b5 6. Bb3 Nf6
7. Nxe5 Nxe5 8. d4 Ba7 9. dxe5 Ng8 10. Qd5 0-1

[Event "Chess game"]
[Date "2021.01.08"]
[White "Player C"]
[Black "Player A"]
[Result "0-1"]

1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Bc5 5. O-O b5 6. Bb3 Nf6
7. Nxe5 Nxe5 8. d4 Ba7 9. dxe5 Ng8 10. Qd5 0-1

答案1

$ awk -v RS= -v ORS='\n\n' '/"Player A"/{c=2} c&&c--' file
[Event "Chess game"]
[Date "2021.01.08"]
[White "Player A"]
[Black "Player B"]
[Result "0-1"]

1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Bc5 5. O-O b5 6. Bb3 Nf6
7. Nxe5 Nxe5 8. d4 Ba7 9. dxe5 Ng8 10. Qd5 0-1

[Event "Chess game"]
[Date "2021.01.08"]
[White "Player C"]
[Black "Player A"]
[Result "0-1"]

1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Bc5 5. O-O b5 6. Bb3 Nf6
7. Nxe5 Nxe5 8. d4 Ba7 9. dxe5 Ng8 10. Qd5 0-1

使用 sed-或 awk-a-line-follow-a-matching-pattern 进行打印有关该习语和相关习语如何工作的详细信息。

我使用于测试Player A你的问题的正则表达式更加强大,并且我使用了RS=<null string>代替,RS='\n\n'因此它可以在任何 awk 中工作,而不仅仅是 gawk 。

答案2

awk处于paragraph模式中

awk -v RS= -v ORS="\n\n" '
  /"Player A"/ { var=NR+1;print }
  var==NR
' file

珀尔paragraph模式(-00

perl -00 -ne '
  print s/\z/<>/re
    if /"Player A"/ && !eof;
' file

sed收集保留空间中的非空行块。一旦确定了目标段落,就从那里开始打印直到最近的空行(=>打印下一条记录)

sed -e '
  /./,/^$/!d
  H;/./d;x;s///
  /"Player A"/!d
  :n;n;/^$/!bn
' file

结果:

[Event "Chess game"]
[Date "2021.01.08"]
[White "Player A"]
[Black "Player B"]
[Result "0-1"]

1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Bc5 5. O-O b5 6. Bb3 Nf6
7. Nxe5 Nxe5 8. d4 Ba7 9. dxe5 Ng8 10. Qd5 0-1

[Event "Chess game"]
[Date "2021.01.08"]
[White "Player C"]
[Black "Player A"]
[Result "0-1"]

1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Bc5 5. O-O b5 6. Bb3 Nf6
7. Nxe5 Nxe5 8. d4 Ba7 9. dxe5 Ng8 10. Qd5 0-1

相关内容