当模式来自变量

时间:2018-02-09 09:45:43

标签: bash sed

我有疑问。当模式来自bash变量时,为什么sed不能正常工作?我准备了简单的bash脚本来为你展示它。有一些已知原因会发生这种情况吗?

#!/usr/bin/env bash

file=/tmp/egz.txt

# Creating example file
echo "First Line" > $file
echo "Second line" >> $file
echo "Third Line" >> $file
echo "Some other line" >> $file

sed_pattern="s|Some other line|Fourth Line|g"

sed -i "s|Some other line|Fourth Line|g" $file

if [[ $? -eq 0 ]]; then
    echo "Sed with pattern works properly."
else
    echo "Sed with pattern works incorrect."
fi

sed -i $sed_pattern $file

if [[ $? -eq 0 ]]; then
    echo "Sed with pattern from variable works properly."
else
    echo "Sed with pattern from variable works incorrect."
fi

在这个脚本的最后一个Ubuntu结果看起来像这样

Sed with pattern works properly.
sed: -e expression #1, char 6: undeterminated `s' command
Sed with pattern from variable works incorrect.

3 个答案:

答案 0 :(得分:1)

$sed_pattern变量附近使用引号。

#!/usr/bin/env bash

file=/tmp/egz.txt

# Creating example file
echo "First Line" > $file
echo "Second line" >> $file
echo "Third Line" >> $file
echo "Some other line" >> $file

sed_pattern="s|Some other line|Fourth Line|g"

sed -i "s|Some other line|Fourth Line|g" $file

if [[ $? -eq 0 ]]; then
    echo "Sed with pattern works properly."
else
    echo "Sed with pattern works incorrect."
fi

sed -i "${sed_pattern}" $file

if [[ $? -eq 0 ]]; then
    echo "Sed with pattern from variable works properly."
else
    echo "Sed with pattern from variable works incorrect."
fi

输出:

Sed with pattern works properly.
Sed with pattern from variable works properly.

答案 1 :(得分:1)

那是因为SED不知道他必须解释变量。 此外,更喜欢变量的简单引号,以避免解释管道。

您可以将代码修改为:

#!/usr/bin/env bash

file=/tmp/egz.txt

# Creating example file
echo "First Line" > $file
echo "Second line" >> $file
echo "Third Line" >> $file
echo "Some other line" >> $file

sed_pattern='s|Some other line|Fourth Line|g'

sed -i "s|Some other line|Fourth Line|g" $file

if [[ $? -eq 0 ]]; then
    echo "Sed with pattern works properly."
else
    echo "Sed with pattern works incorrect."
fi

sed -i "$sed_pattern" $file

if [[ $? -eq 0 ]]; then
    echo "Sed with pattern from variable works properly."
else
    echo "Sed with pattern from variable works incorrect."
fi

答案 2 :(得分:0)

原因是变量sed -i s|Some other line|Fourth Line|g [... rest of cmdline...] 的不加引号扩展导致shell命令的参数由空格字符分隔

实际上,sed的第二次调用就像是

-i

在此cmdline中,参数为s|Someotherline|FourthLine|gs|Somes等。错误消息指的是sed部分,其中df.join()表达式在第6个字符后不完整(确切的错误消息取决于other的实现如何尝试解密乱码命令)。

Always use quotes.