![带有字符串的 awk 段落和 pgn 国际象棋游戏中的以下段落](https://linux22.com/image/188432/%E5%B8%A6%E6%9C%89%E5%AD%97%E7%AC%A6%E4%B8%B2%E7%9A%84%20awk%20%E6%AE%B5%E8%90%BD%E5%92%8C%20pgn%20%E5%9B%BD%E9%99%85%E8%B1%A1%E6%A3%8B%E6%B8%B8%E6%88%8F%E4%B8%AD%E7%9A%84%E4%BB%A5%E4%B8%8B%E6%AE%B5%E8%90%BD.png)
如何使用 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