如何在bash中的变量中使用sed“\”

问题描述 投票:0回答:1

以下

bash
用于将“
$source_product
”替换为“
$source_product
”+“
linefeed
”+“
$target_product
”。

这是 bash 脚本:

source_product="\$(LOCAL_DIR)/source \\"
target_product="\$(LOCAL_DIR)/target \\"

echo "source_product: $source_product"
echo "target_product: $target_product"
echo ""
echo "--- replace source with source+target ---"
echo ""

sed "s|${source_product}|${source_product}\n${target_product}|g" <<< "${source_product}"

这是输出:

source_product: $(LOCAL_DIR)/source \
target_product: $(LOCAL_DIR)/target \

--- replace source with source+target ---

sed: -e expression #1, char 70: unterminated `s' command

这是预期的输出:

source_product: $(LOCAL_DIR)/source \
target_product: $(LOCAL_DIR)/target \

--- replace source with source+target ---

\$(LOCAL_DIR)/source \
\$(LOCAL_DIR)/target \

上面的“

sed
”有什么问题吗?以及如何解决?

bash ubuntu sed
1个回答
0
投票

您需要转义反斜杠(使用更多反斜杠)。您可以直接在

sed
命令中使用 Bash 替换来执行此操作:

sed "s|${source_product//\\/\\\\}|${source_product//\\/\\\\}\n${target_product//\\/\\\\}|g" <<< "${source_product}"
© www.soinside.com 2019 - 2024. All rights reserved.