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?

3
  • echo "var2=$var2" > data.txt ? Is that what you are looking for ? Commented Mar 13, 2018 at 9:18
  • @Aserre Yes, but his instruction deletes the var1=2 in the data.txt. Commented Mar 13, 2018 at 9: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. :) Commented Mar 13, 2018 at 9:48

2 Answers 2

1

I found a solution with the sed command:

echo "Write"
sed -i -e "s/$(grep -Po '(?<=^var2=).*' data.txt)/${var2}/g" data.txt
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.