【问题标题】:Changing a line of text with sed with special characters使用带有特殊字符的 sed 更改一行文本
【发布时间】:2022-10-23 00:16:32
【问题描述】:

标题中的名字说明了一切。但是,我绝对是 sed 命令最差的。所以我正在尝试编辑以下文件: /var/www/html/phpMyAdmin/config.inc.php

我想编辑说

$cfg['Servers'][$i]['AllowRoot'] = false;

进入以下

$cfg['Servers'][$i]['AllowRoot'] = true;

它有很多特殊字符等等,我对 sed 的工作原理一无所知。所以这里有一些我试图专门编辑这一行的命令。

sed -i "/*.AllowRoot.*/\$cfg['Servers'][\$i]['AllowRoot'] = true;/" /var/www/html/phpMyAdmin/config.inc.php
sed -i "/*.AllowRoot.*/$cfg['Servers'][$i]['AllowRoot'] = true;/" /var/www/html/phpMyAdmin/config.inc.php
# this one finds the line successfully and prints it so I know it's got the right string:
sed -n '/AllowRoot/p' /var/www/html/phpMyAdmin/config.inc.php
sed -i "s/'AllowRoot|false'/'AllowRoot|true'/" /var/www/html/phpMyAdmin/config.inc.php

我完全不知道自己在做什么,除了感觉最后一个命令拆分'AllowRoot|false' 确保两个都必须出现在句子中才能返回之外,我并没有学到很多东西。所以按照我的逻辑,我认为将单词false 更改为true 会实现这一点,但没有。其他命令返回......充其量是奇怪的结果,甚至清空文件。或者那是我没有在这里写下的命令之一,我在尝试了 50 次后就迷失了方向。这里的解决方案是什么?

【问题讨论】:

  • 是的,我知道我不应该使用 root 登录到 phpmyadmin,但是在您使用它的短时间内很方便,然后目标是再次将标志设置为 false。
  • 如果你“完全不知道 [你] 在做什么”,也许正确的起点是基本的 sed 教程。一点知识是危险的。在零知识的情况下执行命令可能是灾难性的。

标签: bash sed


【解决方案1】:

[] 需要转义以匹配文字括号,而不是无意中开始括号表达式。这应该有效:

$ sed -i "/$cfg['Servers'][$i]['AllowRoot']/s/false/true/"  /var/www/html/phpMyAdmin/config.inc.php

【讨论】:

  • 对此表示赞同。当然,您需要转义括号。我的例子只是意外地起作用了。也不知道你可以在's'之前创建匹配的文本,使表达更好。
  • 我也不在toftis所说的。绝对棒极了,就像类固醇的魅力一样。孩子们,不要引诱吸毒,但我不得不承认,那里有很多逃跑的机会。非常感谢!
  • 地址可以是行号,也可以是与行文本匹配的正则表达式。
【解决方案2】:

在 sed 中没有多少东西可以逃避。您行中的主要问题是/,您选择了它作为分隔符(最常见,但不是必需的)。我建议您使用#,以下将起作用:

sed -i "s#$cfg['Servers'][$i]['AllowRoot'] = false;<br />#$cfg['Servers'][$i]['AllowRoot'] = true;<br />#g" input.txt

但是,您还需要考虑 bash 解释器。 $i 和 $cfg 将被解释为变量。我的建议是,当您想匹配这样的字符串时,将 sed 表达式放在这样的文本文件中:

cat allow_root_true.sed
s#['Servers'][]['AllowRoot'] = false;<br />#['Servers'][]['AllowRoot'] = true;<br />#g

并使用sed -f 运行命令,如下所示:

sed -i -f allow_root_true.sed input.txt

警告-i 将更改输入文件

【讨论】:

    【解决方案3】:

    sed 无法进行文字字符串匹配,这就是您需要转义这么多字符的原因(请参阅Is it possible to escape regex metacharacters reliably with sed),但 awk 可以:

    $ awk -v str="$cfg['Servers'][$i]['AllowRoot']" 'index($0,str){sub(/false/,"true")} 1' file
        //some text here
        $cfg['Servers'][$i]['AllowRoot'] = true;<br />
        //some more text here
     Run code snippetHide resultsExpand snippet
    

    在上面我们只需要转义$s 以保护它们免受shell 的影响,因为字符串包含在"s 中以允许它包含's。

    【讨论】:

      猜你喜欢
      • 2018-07-02
      • 2018-11-14
      • 1970-01-01
      • 1970-01-01
      • 2017-05-05
      • 2018-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多