Ubuntu: How can I get and change a value of a line inside of a file if the value of such line is unknown by me?


What I am trying to do is: There's a file, inside of it, there's a line (it surely will be there, 100%) in this model:


Where the value is numerical and unknown by me because it changes between device and device... I need to, somehow, get the xxx value and replace it with another value given by the user via a TextField (I'm using Java for this, it's for an Android application, but it's pure shell script anyway).

Is valid:

  1. Find and delete the whole line and replace with the full line e.g delete name_of_the_value=xxx and replace it with name_of_the_value=user_value
  2. Replace only the xxx (value) part
  3. Comment with '#' any existing matching lines and write the full line at the bottom of the file

But how can I use echo, sed or awk if I don't know the value?


Assuming the part for user_value is always 3 characters long you can do it like this:

sed "s/name_of_the_value=.{0,3}/name_of_the_value=$new_value/"  

Or if you be sure there is nothing behind in that line you aswell could use:

sed "s/name_of_the_value=.*/name_of_the_value=$new_value/"  

I hope i got that REGEX right, I'm no pro in this. So the value should be all the time 3 characters long best in hex format because decimal doesn't be always 3 characters long in cases below 100. The second case should work even i the number is below 100 but it assumes the whole name_of_the_value=user_value part is in a line of its own. Now testing this in terminal the output looks like this for the second case:

video@NAUTH:~$ echo "name_of_the_value=xxx" | sed "s/name_of_the_value=.*/name_of_the_value=$USER/"  name_of_the_value=video  

Of course you need to pipe the output back into the file, or use a temporary file to swap around. You could use:

sed "s/name_of_the_value=.*/name_of_the_value=$new_value/" /input_file | sponge /input_file  

Sed only changes the output while reading the file, not writing it, sponge saves the output then until you are through and writes the changes back.

If you don't want to or can't use sponge write in a second file and then switch them like this chain of commands.

sed "s/name_of_the_value=.*/name_of_the_value=$new_value/" /input_file > /output_file  rm -v /input_file  mv -v /output_file /input_file  

As @kos pointed out in the comment you can as well use the -i flag of the sed command to write back into the input file without the use of a temporary file or sponge:

sed -i "s/name_of_the_value=.*/name_of_the_value=$new_value/" /input_file  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »