如何使用 sed 替换多行字符串? [英] How to use sed to replace multiline string?

查看:129
本文介绍了如何使用 sed 替换多行字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 bash sed 命令更改此字符串:

How can I use the bash sed command to change this string:

<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>

NOTE 1: I don't just want to target the string 'AllowOverride None' because there are other occurrences in the file that should not be changed. I need to target the entire string starting with <Directory /var/www>

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

NOTE 2: I also need to overwrite the file. So, take that into account in your answer. And provide different versions for GNU/non-GNU versions of sed just in case.

推荐答案

我意识到这不是你问的问题,也许不使用 sed 值得?

I realize this is not what you asked by maybe its worth not using sed?

python 解决方案怎么样?它遍历作为第一个参数传递给脚本的目录,并在您编写时替换完全 元素,同时更改NoneAll 并将更改写回文件.它还可以使用不同的缩进级别,同时保留原始缩进.适用于 python2 和 python3.

How about a python solution? It walks directory passed as first parameter to script and replaces exactly <Directory element as you wrote it while only changing None to All and writes changes back to the file. It will also work with different indentation levels while preserving original indentation. Works on both python2 and python3.

毕竟我假设如果你有 sed 你可能也有 python.

After all i am assuming if you have sed you probably have python too.

#!/usr/bin/env python
import re

r = re.compile(r'(<Directory /var/www/>\s+Options Indexes FollowSymLinks\s+AllowOverride )None(\s+Require all granted\s+</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'\1All\2', fp.read())
            with open(file_path, 'w+') as fp:
                fp.write(data)

这篇关于如何使用 sed 替换多行字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆