Change variable value inside text file with Sed

18,807

Solution 1

Say you wanted to change the value of Var2 from 'smelf' to 'smurf', you could use:

bash$ sed -i 's/Var2=.*/Var2=smurf/' file.txt

Solution 2

In case you want more complex substitution:

sed_param=s/Var1=.*/Var1=${NEW_VALUE}/  
sed -i "$sed_param" file.txt
Share:
18,807
HobbitOfShire
Author by

HobbitOfShire

C Developer

Updated on July 27, 2022

Comments

  • HobbitOfShire
    HobbitOfShire almost 2 years

    I have a text file containting this

    Var1=ofzer
    Var2=smelf
    ..
    ..
    VarN=mskfm
    

    I want to change the value of one of my variables using Sed. How is that possible?

  • Olie
    Olie over 9 years
    Suppose I want to set it to ${NEW_VALUE}? I can't use ${var} inside of single quotes and, if I switch to double-quotes, the .* part doesn't work (does it?!) So now what?
  • Alberto Salvia Novella
    Alberto Salvia Novella almost 3 years
    You can use double quotes.