I am trying to replace a line in file and am running in to issues.
Original File:
export PS1='h:w$ '
Command I am running:
perl -pi -e 's~PS1.*~PS1="n[e[32;1m][[e[37;1m]u@h:[e[37;1m]w[e[32;1m]]\$ [e[0m]~g' ~/.bashrc
Error message:
syntax error at -e line 1, near "e[" Execution of -e aborted due to compilation errors.
I also tried sed:
sed -i 's~PS1.*~PS1="n[e[32;1m][[e[37;1m]u@h:[e[37;1m]w[e[32;1m]]\$ [e[0m]~g' ~/.bashrc
Result with Sed:
export PS1=" [e[32;1m][[e[37;1m]@h:[e[37;1m]w[e[32;1m]]$ [e[0m]
Expected Result File:
export PS1="n[e[32;1m][[e[37;1m]u@h:[e[37;1m]w[e[32;1m]]\$ [e[0m]"
End Result
This doesn’t have much to do with the question except to show folks what the PS1 will look like when working properly
Advertisement
Answer
For sed, you have to escape each backslash with another backslash for them to be treated literally.
The s command additionally requires you to escape the delimiter and &, so it’s easier to use the c command, so that doubling backslashes is the only requirement:
sed -i '/PS1/c export PS1="\n\[\e[32;1m\][\[\e[37;1m\]\u@\h:\[\e[37;1m\]\w\[\e[32;1m\]]\\$ \[\e[0m\]" ' file.txt
If file.txt contains:
hello PS1=foo world
then after running this command, it will contain:
hello export PS1="n[e[32;1m][[e[37;1m]u@h:[e[37;1m]w[e[32;1m]]\$ [e[0m]" world
