skip to Main Content

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


  1. That is because of the quotes that you use, the -n option ans the absence of a p 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 the p:

    sed -ni "s/$myip/$newip/p" abc
    

    Note that, if you want to kep the lines that do not match, you just remove the -n.

    Login or Signup to reply.
  2. There are two errors in your script.

    1. When you enclose a string into single quotes ', the substitution of the bash variables will not happen. You have to use double quotes ".

    2. If you use the -n option, you will produce no output except with the command p that you don’t use.

    The correct script is:

    #!/bin/bash
    myip=1.2.3.4; newip=5.6.7.8
    sed -i "s/$myip/$newip/" abc 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search