本文介绍了用 sed 替换复杂字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Trying to find and replace PS1="[\u@\h \W]\\$ " with something like: PS1='\[\e[0;31m\][\u@\h \W]\$\[\e[m\] ' in /etc/bashrc file with sed has been failed because of two levels of interpretion: bash and sed iteself.

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

How should I replace those complex strings using bash and sed?

推荐答案

我逐个构建了表达式,最多如下:

I built the expression piece by piece, up to the following:

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\] '\')

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

Here we are matching correctly the whole input, so we can start outputting:

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\] '\')

这篇关于用 sed 替换复杂字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 04:51