加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

如何使用sed替换多行字符串?

发布时间:2020-12-14 02:12:05 所属栏目:Linux 来源:网络整理
导读:如何使用bash sed命令更改此字符串: Directory /var/www/ Options Indexes FollowSymLinks AllowOverride None Require all granted/Directory 进入以下字符串? (仅更改第3行字符串) Directory /var/www/ Options Indexes FollowSymLinks AllowOverride Al
如何使用bash sed命令更改此字符串:

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

进入以下字符串? (仅更改第3行字符串)

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

注1:我不只是想要将字符串’AllowOverride None’作为目标,因为文件中还有其他一些不应该更改的事件.我需要以< Directory / var / www>开头的整个字符串为目标.

注2:我还需要覆盖该文件.所以,在你的答案中考虑到这一点.并提供不同版本的GNU /非GNU版本的sed以防万一.

解决方法

我意识到这不是你问的可能它不值得使用sed吗?

python解决方案怎么样?它将作为第一个参数传递的目录传递给脚本,并在编写时完全替换< Directory元素,同时仅将None更改为All并将更改写回文件.它还可以使用不同的缩进级别,同时保留原始缩进.适用于python2和python3. 毕竟我假设你有sed你也可能有python.

#!/usr/bin/env python
import re

r = re.compile(r'(<Directory /var/www/>s+Options Indexes FollowSymLinkss+AllowOverride )None(s+Require all granteds+</Directory>)',re.MULTILINE)

for root,dirs,files in os.walk(sys.argv[1]):
    for file_name in files:
        if file_name.endswith('.conf'):
            file_path = os.path.join(root,file_name)
            with open(file_path) as fp:
                data = r.sub(r'1All2',fp.read())
            with open(file_path,'w+') as fp:
                fp.write(data)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读