bash替换文件中包含特殊字符的字符串

bash替换文件中包含特殊字符的字符串,bash,sed,Bash,Sed,正如我在标题中所说,我试图替换文件中包含特殊字符的字符串,现在的想法是在“infofile”的每一行上循环,其中包含许多行:whatiwanttoreplace,replacer。 一旦我有了这个,我想对一个特定的文件执行sed,以替换所有出现的字符串->“whatiwanttoreplace”为->“replacer”。 我的代码: infofile=“inforfilepath” replacefile=“replacefilepath” 而IFS=读取-r行 做 what2replace=

正如我在标题中所说,我试图替换文件中包含特殊字符的字符串,现在的想法是在“infofile”的每一行上循环,其中包含许多行:whatiwanttoreplacereplacer。 一旦我有了这个,我想对一个特定的文件执行sed,以替换所有出现的字符串->“whatiwanttoreplace”为->“replacer”。 我的代码:

infofile=“inforfilepath”
replacefile=“replacefilepath”
而IFS=读取-r行
做
what2replace=“a”#$(echo“$line”| cut-d”,“-f1);
replacer=“b\\”#$(回显“$line”| cut-d”,“-f2);
sed-i-e“s/$what2replace/$replacer/g”“$replacefile”
#sed-i-e“s/'$what2replace'/'$replacer'/g”“$replacefile”
#sed-i-e“s@$what2替换@$replacer@g“$replacefile”
#sed-i-e s/$what2replace/$replacer/g'$replacefile“
#sed-i-e“s/${what2replace}/${replacer}/g”“$replacefile”
#${replacefile//what2replace/replace}
完成<“$infofile”
如您所见,要替换的字符串和我要替换的字符串可能包含特殊字符,所有注释行都是我尝试过的内容(我在网上看到的内容),但仍然不清楚

对于一些人,我犯了这样的错误: sed:-e表达式#1,字符8:未终止的's'命令 对一些人来说,什么也没发生

我真的需要你的帮助

编辑:输入和输出: 很难给出输入和输出,因为我尝试过的所有变量都有相同的东西,没有改变任何东西,唯一给出上述错误的是带有@的变量。 谢谢你的努力。

你可以这样试试

what='a';to='b\\\\';echo 'sdev adfc xdae' | sed "s/${what}/${to}/g"
输出

sdev b\\dfc xdb\\e
你可以这样试试

what='a';to='b\\\\';echo 'sdev adfc xdae' | sed "s/${what}/${to}/g"
输出

sdev b\\dfc xdb\\e

你搞错了——你试图用一个工具sed来替换文本字符串,这个工具没有处理文本字符串的功能。请参阅,了解强制sed执行您想要的操作所需的复杂混乱,以及为什么要避免用于操纵文本的shell循环

只需使用awk,因为它本身隐式地具有文字字符串函数和循环:

awk '
NR==FNR{map[$1]=$2; next}
{
    for (old in map) {
        new = map[old]
        head = ""
        tail = $0
        while ( s = index(tail,old) ) {
            head = head substr(tail,1,s-1) new
            tail = substr(tail,s+length(old))
        }
        $0 = head tail
    }
}
' "$infofile" "$replacefile"

以上内容当然未经测试,因为您没有提供任何示例输入/输出。

您找错了方向-您试图使用一个没有处理文本字符串功能的工具sed进行文本字符串替换。请参阅,了解强制sed执行您想要的操作所需的复杂混乱,以及为什么要避免用于操纵文本的shell循环

只需使用awk,因为它本身隐式地具有文字字符串函数和循环:

awk '
NR==FNR{map[$1]=$2; next}
{
    for (old in map) {
        new = map[old]
        head = ""
        tail = $0
        while ( s = index(tail,old) ) {
            head = head substr(tail,1,s-1) new
            tail = substr(tail,s+length(old))
        }
        $0 = head tail
    }
}
' "$infofile" "$replacefile"

上述内容当然未经测试,因为您没有提供任何示例输入/输出。

您是否可以编辑问题并提供一些示例输入数据和预期输出。此外,如果您检查,可能会有帮助…您是否可以编辑问题并提供一些示例输入数据和预期输出。此外,如果您检查,可能会有帮助…谢谢,但是我需要命令来处理一个文件,我不能回显每一行,这将花费永远的时间。我尝试了那个特殊的“sed”变体(sed“s/${what}/${to}/g”).what='a';to='b\\\';sed“s/${what}/${to}/g”“${infofile}”>“${replacefile}”谢谢,但我需要命令来处理文件,我无法回显每一行,这将花费很长时间。我尝试了那个特殊的“sed”变体(sed“s/${what}/${to}/g”).what='a';to='b\\\';sed“s/${what}/${to}/g”“${infofile}>“${replacefile}”谢谢你的回答,你能帮我理解你的代码吗?这样下次我就能自己站起来了。再次感谢。谢谢你的回答,你能帮我理解你的代码吗?这样下次我就能自己站起来了。再次感谢。