regex - egrep 匹配多行

标签 regex bash grep

我在多个主机上有多个 Apache vHost 配置。我正在尝试编写一个 Bash 脚本,它将迭代每个主机并搜索 .conf对每个文件进行归档,取出第一个(仅第一个)<VirtualHost>堵塞。我尝试编写一个正则表达式来匹配它,但它不起作用。这是我尝试过的代码:

    #!/bin/bash
    egrep -o '(\<VirtualHost\>)(.*)(\<\/VirtualHost\>)' -m1

.*与换行符不匹配,我什至尝试过:

    #!/bin/bash
    egrep -o '(\<VirtualHost\>)(.*[\S]*)(\<\/VirtualHost\>)' -m1

我还是一无所获。 :-(

我不明白我在这里做错了什么。以下是我尝试匹配的数据示例:

    <VirtualHost apache-frontend:80>
            ServerAdmin     <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="701d090319041530141f1d11191e5e131f1d" rel="noreferrer noopener nofollow">[email protected]</a>
            ServerName      domain.com
            DocumentRoot    /path/to/my/doc/root

            RewriteEngine   On
            Include         include.d/global/rewrite.conf
            RewriteRule     ^(.*)$ http://www.domain.com$1 [R=301,L]
    </VirtualHost>

    <VirtualHost apache-frontend:80>
            ServerAdmin     <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="335e4a405a475673575c5e525a5d1d505c5e" rel="noreferrer noopener nofollow">[email protected]</a>
            ServerName      domain.com
            DocumentRoot    /path/to/my/doc/root

            RewriteEngine   On
            Include         include.d/global/rewrite.conf
            RewriteRule     ^(.*)$ http://www.domain.com$1 [R=301,L]
    </VirtualHost>

    <VirtualHost apache-frontend:80>
            ServerAdmin     <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="137e6a607a677653777c7e727a7d3d707c7e" rel="noreferrer noopener nofollow">[email protected]</a>
            ServerName      domain.com
            DocumentRoot    /path/to/my/doc/root

            RewriteEngine   On
            Include         include.d/global/rewrite.conf
            RewriteRule     ^(.*)$ http://www.domain.com$1 [R=301,L]
    </VirtualHost>

最佳答案

此 oneliner 仅从配置文件中提取第一个 VirtualHost block :

awk '/<VirtualHost/,/<\/VirtualHost>/{print $0} /<\/VirtualHost>/{exit}' < vhostconf

关于regex - egrep 匹配多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35930359/

相关文章:

linux - 如何通过将 Grep 输出管道传输到 Sed 来添加变量模式?

linux - perl grep 和 cli grep 之间的不一致

linux - 如何索引文本文件以缩短 grep 时间

javascript - 为什么以下文件扩展名正则表达式不匹配?

mysql - Bash MySQL 查询

以 char 开头但不以该 char 结尾的单词的正则表达式

bash - alias hello ='echo Hello' - 为什么这在重启后不起作用?

linux - 提取 2 个子串之间的子串

python - 如何使用正则表达式删除 python 中的逗号、括号?

C++::Boost::Regex 迭代子匹配