用sed替换复杂的字符串

时间:2015-07-07 09:27:57

标签: bash replace sed

尝试使用以下内容查找和替换PS1="[\u@\h \W]\\$ ":  带有sed的PS1='\[\e[0;31m\][\u@\h \W]\$\[\e[m\] '文件中的/etc/bashrc由于两个级别的解释而失败了:bash和sed iteself。

我应该如何使用bash和sed替换那些复杂的字符串?

1 个答案:

答案 0 :(得分:1)

我逐个构建了表达式,直到以下内容:

sed 's/PS1="\[\\u@\\h \\W]\\\\\$ "/PS1='\''\\[\\e[0;31m\\][\\u@\\h \\W]\\$\\[\\e[m\\] '\'/

以下是一些步骤:

echo 'PS1="[\u@\h \W]\\$ "' \
    | diff <(sed s/a/b/)
           <(PS1=\''\[\e[0;31m\][\u@\h \W]\$\[\e[m\] '\')

echo 'PS1="[\u@\h \W]\\$ "' \
    | diff <(sed 's/PS1="\[//')
           <(echo PS1=\''\[\e[0;31m\][\u@\h \W]\$\[\e[m\] '\')


echo 'PS1="[\u@\h \W]\\$ "' \
    | diff <(sed 's/PS1="\[\\u@\\h//')
           <(echo PS1=\''\[\e[0;31m\][\u@\h \W]\$\[\e[m\] '\')

echo 'PS1="[\u@\h \W]\\$ "' \
    | diff <(sed 's/PS1="\[\\u@\\h \\W]//')
           <(echo PS1=\''\[\e[0;31m\][\u@\h \W]\$\[\e[m\] '\')

echo 'PS1="[\u@\h \W]\\$ "' \
    | diff <(sed 's/PS1="\[\\u@\\h \\W]\\\\\$ "//')
           <(echo PS1=\''\[\e[0;31m\][\u@\h \W]\$\[\e[m\] '\')

这里我们正确匹配整个输入,因此我们可以开始输出:

echo 'PS1="[\u@\h \W]\\$ "' \
    | diff <(sed 's/PS1="\[\\u@\\h \\W]\\\\\$ "/PS1='\''/')
           <(echo PS1=\''\[\e[0;31m\][\u@\h \W]\$\[\e[m\] '\')

echo 'PS1="[\u@\h \W]\\$ "' \
    | diff <(sed 's/PS1="\[\\u@\\h \\W]\\\\\$ "/PS1='\''\\[\\e/')
           <(echo PS1=\''\[\e[0;31m\][\u@\h \W]\$\[\e[m\] '\')

echo 'PS1="[\u@\h \W]\\$ "' \
    | diff <(sed 's/PS1="\[\\u@\\h \\W]\\\\\$ "/PS1='\''\\[\\e[0;31m\\][\\u@\\h \\W]\\$\\[\\e[m\\] /')
           <(echo PS1=\''\[\e[0;31m\][\u@\h \W]\$\[\e[m\] '\')

echo 'PS1="[\u@\h \W]\\$ "' \
    | diff <(sed 's/PS1="\[\\u@\\h \\W]\\\\\$ "/PS1='\''\\[\\e[0;31m\\][\\u@\\h \\W]\\$\\[\\e[m\\] '\'/)
           <(echo PS1=\''\[\e[0;31m\][\u@\h \W]\$\[\e[m\] '\')