aysabzevar
aysabzevar

Reputation: 1172

replace complex string with 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.

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

Upvotes: 0

Views: 473

Answers (1)

choroba
choroba

Reputation: 241898

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

Here are some of the steps:

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

Upvotes: 1

Related Questions