Linux

帶有字元串的awk段落和pgn國際象棋遊戲中的以下段落

  • February 22, 2021

如何獲得帶有字元串的段落和帶有 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
$ 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

請參閱print-with-sed-or-awk-a-line-following-a-matching-pattern以了解有關該模式和相關習語如何工作的詳細資訊。

我使Player A從您的問題中測試的正則表達式更加健壯,我使用RS=<null string>了而不是RS='\n\n'因此它可以在任何 awk 中工作,而不僅僅是 gawk。

引用自:https://unix.stackexchange.com/questions/635698