我如何逃避嵌入在bash脚本sed脚本反斜线 [英] How do I escape backslashes in a sed script embedded in a bash script
问题描述
我想通过在bash脚本sed脚本编辑一个文件。我想这是便于以后维护;很容易理解和修改。替换字符串如下:
I want to edit a file via a sed script in a bash script. I want this to be easy to maintain later; easy to understand and modify. The replacement string looks like:
PS1='\[\e[1;32m\][\u@\h \W]\$\[\e[0m\]'
在一个完美的世界,这将是这样的:
In a perfect world, it would like this:
sed -i "s/^PS1.*$/PS1='\[\e[1;32m\][\u@\h \W]\$\[\e[0m\]'/g" /etc/skel/.bashrc
问题是,bash和SED被剥离出 \\
给该文件在以下结果:
PS1='[e[1;32m][@h W]$[e[0m]'
显然单引号,不能使用。蛮力解决方案是使用逃逸,但对于这个工作,我得到一个非常难看的行:
Obviously single quotes can't be used. A brute force solution is to use escapes, but for this to work I get a really ugly looking line:
sed -i "s/^PS1.*$/PS1='\\\\[\\\\e[1;32m\\\\][\\\\u@\\\\h \\\\W]\\\\$\\\\[\\\\e[0m\\\\]'/g" /etc/skel/.bashrc
我想剧本是可读的,自我包含的(不使用外部文件)。任何替代于上述
I want the script to be readable and self contained (not using external files). Any alternatives to the above?
推荐答案
在可读,可编辑的形式插入猛砸的printf可以添加必要逃逸,留下的字符串。
Bash's printf can add the necessary escapes, leaving the string to be inserted in an readable, editable form.
sed -i "s/^PS1.*$/$(printf "%q" "PS1='\[\e[1;32m\][\u@\h \W]$\[\e[0m\]'")/g" /etc/skel/.bashrc
不是要坚持这一切在同一行,使整个事情更加清楚。
Not trying to stick it all on one line makes the whole thing clearer.
REPL=$(printf "%q" "PS1='\[\e[1;32m\][\u@\h \W]$\[\e[0m\]'")
sed -i "s/^PS1.*$/$REPL/g" /etc/skel/.bashrc
这篇关于我如何逃避嵌入在bash脚本sed脚本反斜线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!