bash sed truncates file instead of replacing text.
I want to update variables in bashrc source with sed but to my surprise sed truncates the file.
For testing i have a little file abc:
export PATH=$PATH:$HOME/bin:$JAVA_HOME/bin
export myip=1.2.3.4
and this test script:
#!/bin/bash
myip=1.2.3.4; newip=5.6.7.8
sed -ni 's/$myip/$newip/' abc
running the script leaves abc empty.
Why is this so?
I am using Ubuntu 22.04 on an Intel I7.
2
Answers
That is because of the quotes that you use, the
-n
option ans the absence of ap
behind the substitute.In bash, the single quote
'
makes sure that the text is taken literally, without variable expansion. So, you would probably want to use double quotes"
.Because yo use
-n
, you will probably want to print the line that you want to keep as well with thep
:Note that, if you want to kep the lines that do not match, you just remove the
-n
.There are two errors in your script.
When you enclose a string into single quotes
'
, the substitution of the bash variables will not happen. You have to use double quotes"
.If you use the
-n
option, you will produce no output except with the commandp
that you don’t use.The correct script is: