I am trying to replace a line in file and am running in to issues.
Original File:
JavaScript
x
export PS1='h:w$ '
Command I am running:
JavaScript
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:
JavaScript
syntax error at -e line 1, near "e["
Execution of -e aborted due to compilation errors.
I also tried sed:
JavaScript
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:
JavaScript
export PS1="
[e[32;1m][[e[37;1m]@h:[e[37;1m]w[e[32;1m]]$ [e[0m]
Expected Result File:
JavaScript
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:
JavaScript
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:
JavaScript
hello
PS1=foo
world
then after running this command, it will contain:
JavaScript
hello
export PS1="n[e[32;1m][[e[37;1m]u@h:[e[37;1m]w[e[32;1m]]\$ [e[0m]"
world