英文:
Replace a string containing arbitrary special characters
问题
我正在尝试使用 sed 在文本文件中替换一个字符串。这个字符串可能包含任何特殊字符,如 ., /, $ 等。然而,我希望将这样的字符串 字面地 替换,即不将 ., /, $ 等解释为特殊字符。
所以,简单的指令
sed -i s|$old|$new| "$path_to_file"
如果我想用 20.9 替换 20.8,就不能按照我期望的方式工作。
当然,在启动使用这个 sed 的脚本之前,我不知道用户会在哪里放置特殊字符。
有没有办法使用 sed 或其他工具(如 perl、awk 等)来实现这一点?
谢谢!
英文:
I'm trying to replace a string inside a text file using sed. This string could contain any special character like ., /, $, etc. However, I'm interested to replace such a string literally, that is to not interpret ., /, $, etc. as special characters.
So, the simple instruction
sed -i s|$old|$new| "$path_to_file"
doesn't work as I expect if I want to replace 20.8 with 20.9 for example.
Of course, before starting the script that uses this sed, I don't have any idea where the special characters will be placed by the user.
Is there a way to do this with sed or any other tools (perl, awk, etc.)?
Thanks!
答案1
得分: 0
如果文件不包含空值并且可以轻松地放入内存中,您可以直接使用bash参数扩展:
data=$(<"文件路径")
echo "${data//"$旧值"/"$新值"}" >"文件路径"
不要忘记双引号,它们会禁用特殊的模式字符。
注意:
date=$(...)剥离末尾的换行符;使用mapfile来保留它们。echo可能在某些边界条件下产生意外的输出;使用printf来避免这些问题。
因此,稍微长一些但改进很多的版本如下:
mapfile -d '' data <"文件路径"
printf '%s' "${data//"$旧值"/"$新值"}" >"文件路径"
英文:
If file does not contain nulls and will fit comfortably in memory, you can just use bash parameter expansion directly:
data=$(<"$path_to_file")
echo "${data//"$old"/"$new"}" >"$path_to_file"
Don't forget the double-quotes, they disable special pattern characters.
Notes:
date=$(...)strips trailing newlines; usemapfileto keep themechocan produce unintended output in some corner conditions; useprintfto avoid them
So, slightly longer but much improved version:
mapfile -d '' data <"$path_to_file"
printf '%s' "${data//"$old"/"$new"}" >"$path_to_file"
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论