【发布时间】:2018-11-04 02:44:21
【问题描述】:
我想要一种使用 sed 命令进行替换的方法,该命令转义要在另一个 sed 命令中使用的“模式”(字符串)。 此转义过程必须包括对多行字符串模式的处理。
为了说明,我提供了下面的代码。它工作得很好(到目前为止测试良好),但是当我们有多行字符串时会失败(参见“STRING_TO_ESCAPE”)。
#!/bin/bash
# Escape TARGET_STRING.
read -r -d '' STRING_TO_ESCAPE <<'HEREDOC'
$N = "magic_quotes_gpc = <b>"._("On")."</b>";
$D = _("Increase your server security by setting magic_quotes_gpc to 'on'. PHP will escape all quotes in strings in this case.");
$S = _("Search for 'magic_quotes_gpc' in your php.ini and set it to 'On'.");
$R = ini_get('magic_quotes_gpc');
$M = TRUE;
$this->config_checks[] = array("NAME" => $N , "DESC" => $D , "RESULT" => $R , "SOLUTION" => $S , "MUST" => $M );
HEREDOC
ESCAPED_STRING=$(echo "'${STRING_TO_ESCAPE}'" | sed 's/[]\/$*.^|[]/\\&/g')
ESCAPED_STRING=${ESCAPED_STRING%?}
TARGET_STRING=${ESCAPED_STRING#?}
# NOTE: The single quotes in "'${STRING_TO_ESCAPE}'" serve to prevent spaces
# being "lost" at the beginning and end of the string! The manipulations with
# "ESCAPED_STRING" are used to remove them. When we use sed with the file being
# input (flag "-i") this problem does not occur.
# Escape REPLACE_STRING.
read -r -d '' STRING_TO_ESCAPE <<'HEREDOC'
/* NOTE: "Magic_quotes_gpc" is no longer required. We taught GOsa2 to deal with it (see /usr/share/gosa/html/main.php). By Questor */
/* Automatic quoting must be turned on */
/* $N = "magic_quotes_gpc = <b>"._("On")."</b>";
$D = _("Increase your server security by setting magic_quotes_gpc to 'on'. PHP will escape all quotes in strings in this case.");
$S = _("Search for 'magic_quotes_gpc' in your php.ini and set it to 'On'.");
$R = ini_get('magic_quotes_gpc');
$M = TRUE;
$this->config_checks[] = array("NAME" => $N , "DESC" => $D , "RESULT" => $R , "SOLUTION" => $S , "MUST" => $M ); */
HEREDOC
ESCAPED_STRING=$(echo "'${STRING_TO_ESCAPE}'" | sed 's/[]\/$*.^|[]/\\&/g')
ESCAPED_STRING=${ESCAPED_STRING%?}
REPLACE_STRING=${ESCAPED_STRING#?}
# Do the replace.
STRING_TO_MODIFY=$(cat file_name.txt)
MODIFIED_STRING=$(echo "'${STRING_TO_MODIFY}'" | sed 's/$TARGET_STRING/$REPLACE_STRING/g')
MODIFIED_STRING=${MODIFIED_STRING%?}
MODIFIED_STRING=${MODIFIED_STRING#?}
echo "$MODIFIED_STRING"
谢谢! =D
【问题讨论】:
-
这看起来使用
patch而不是sed要容易得多。 -
我不确定我是否遵循您想要完成的目标。 如何在第二个
sed命令中使用转义字符串?你是说你想要一种方法来检测与原始字符串的文字匹配吗? -
@John Bollinger 我会尽量澄清。我想要的是能够在 sed 的路径中使用最初具有多行的字符串。我想要的是一个 pathern sed,它用多行转义这个字符串,以便在另一个 sed 中使用。示例:
ESCAPED_STRING=$(echo "'${STRING_TO_ESCAPE}'" | sed 's/[]\/$*.^|[]/\\&/g') -
是的,@EduardoLucio,我已经在您的示例代码中看到了这一点。据我所知,这似乎是您现在用来执行转义的基于
sed的机制。我在问你想如何使用它的 result,或者我们可能建议的任何替代方案。正如我已经写的答案所描述的那样,我怀疑您的问题根本不在于转义,而在于您正在使用结果的sed程序。 -
这个问题似乎很难理解。请提供示例输入和所需的输出。