使用 bash 解析多行输出

使用 bash 解析多行输出

我有一个程序将创建一个带有如下输出的文本文件:

...
AF
Aug 05 16:27:01.310 [notice] Tor 0.3.5.8 running on Linux with Libevent 2.1.8-stable, OpenSSL 1.1.1c, Zlib 1.2.11, Liblzma 5.2.4, and Libzstd 1.3.8.
Aug 05 16:27:01.310 [notice] Tor can't help you if you use it wrong! Learn how to be safe at https://www.torproject.org/download/download#warning
Aug 05 16:27:01.311 [notice] Read configuration file "/etc/tor/torrc".
Aug 05 16:27:01.314 [notice] Opening Socks listener on 127.0.0.1:9050
Aug 05 16:27:01.314 [notice] Opened Socks listener on 127.0.0.1:9050
Aug 05 16:27:01.000 [notice] Parsing GEOIP IPv4 file /usr/share/tor/geoip.
Aug 05 16:27:01.000 [notice] Parsing GEOIP IPv6 file /usr/share/tor/geoip6.
Aug 05 16:27:01.000 [notice] Bootstrapped 0%: Starting
Aug 05 16:27:01.000 [notice] Starting with guard context "default"
Aug 05 16:27:11.000 [notice] Catching signal TERM, exiting cleanly.

AX
Aug 05 16:27:11.333 [notice] Tor 0.3.5.8 running on Linux with Libevent 2.1.8-stable, OpenSSL 1.1.1c, Zlib 1.2.11, Liblzma 5.2.4, and Libzstd 1.3.8.
Aug 05 16:27:11.333 [notice] Tor can't help you if you use it wrong! Learn how to be safe at https://www.torproject.org/download/download#warning
Aug 05 16:27:11.333 [notice] Read configuration file "/etc/tor/torrc".
Aug 05 16:27:11.338 [notice] Opening Socks listener on 127.0.0.1:9050
Aug 05 16:27:11.338 [notice] Opened Socks listener on 127.0.0.1:9050
Aug 05 16:27:11.000 [notice] Parsing GEOIP IPv4 file /usr/share/tor/geoip.
Aug 05 16:27:11.000 [notice] Parsing GEOIP IPv6 file /usr/share/tor/geoip6.
Aug 05 16:27:11.000 [notice] Bootstrapped 0%: Starting
Aug 05 16:27:12.000 [notice] Starting with guard context "default"
Aug 05 16:27:21.000 [notice] Catching signal TERM, exiting cleanly.
...

本质上,它会检查 TOR 是否可以通过不同的国家/地区进行连接。我将其设置为在段落前输出 ISO alpha-2 代码,然后输出一个空的返回行。

我如何创建一个程序,可以解析每个单独的段落,搜索文本“100%”,如果存在,则使用 bash“>>”将 alpha-2 代码(段落上方)复制到另一个文件中

答案1

如果您的输入由一个或多个空行分隔的记录组成,那么您可以使用 awk 或 perl段落模式

awk -vRS= '/100%/ {print $1}' file >> newfile

或者

perl -00anE 'say $F[0] if /100%/' file >> newfile

相关内容