1

I want to be able to read and write to a file with a bash script. I am able to read the variables from the file but I am not sure how to write to it.

The file data.txt contains the variable names and their values like this:

var1=2
var2=3

The shell script looks like this:

#!bin/bash

echo "Read"
var1=$(grep -Po "(?<=^var1=).*" data.txt)

echo "Do Something"
var2=${var1}

echo "Write"
# var2 should be saved in data.txt like this: var2=<Here is the Value>, e.g. var2=2

I can read the specific values of the variables with the grep command, which I got from this answer. But I am not sure how to implement the functionality to be able to save the values of the variables at the correct position (see the last comment in the bash script).
The variable names are unique in data.txt.

Any ideas how to achieve this?

jww
  • 97,681
  • 90
  • 411
  • 885
Vuks
  • 801
  • 1
  • 7
  • 24
  • `echo "var2=$var2" > data.txt` ? Is that what you are looking for ? – Aserre Mar 13 '18 at 09:18
  • @Aserre Yes, but his instruction deletes the `var1=2` in the `data.txt`. – Vuks Mar 13 '18 at 09:24
  • @Aserre No need to get so harsh, I appreciate your effort and was just commenting about what happens. And the `>>` appends the line instead of replacing it. But neverless I found a solution and will post it in a second. Thanks for your input. :) – Vuks Mar 13 '18 at 09:48

2 Answers2

1

I found a solution with the sed command:

echo "Write"
sed -i -e "s/$(grep -Po '(?<=^var2=).*' data.txt)/${var2}/g" data.txt
Vuks
  • 801
  • 1
  • 7
  • 24
0

You can use sed to do the job.

!/bin/bash

echo "Read"
var1=$(grep -Po "(?<=^var1=).*" data.txt)

echo "Do Something"
var2=${var1}

echo "Write"
sed -i "/var2/ s/.*/var2=${var2}/" data.txt # replace the line contains 'var2' with var2=2

I assume you use GNU sed, for BSD sed, you need to feed an extra suffix to -i.

bigeast
  • 627
  • 5
  • 14
  • Sorry, I saw your answer after I posted mine. They are very similar, but yours doesn't replace the value but instead appends it to the existing value. – Vuks Mar 13 '18 at 09:54
  • Yes, it does. `"/var2/ s/.*/var2=${var2}/"` changed the whole line that contains "var2" into "var2=2", so now the "var2=3" will become "var2=2", which is exactly what you want. – bigeast Mar 13 '18 at 10:34