Shell Search and Replace variable in configuration file using sed

Hello,

I have tried and tried messing around with sed and regular-expressions but I just cannot find a solution. So I thought I would post this to the forum for some help...

I am in need of searching for and replacing, name/value pairs in a configuration file. An example would look something like this...

Apache config:
variable = value # Comment.

Nothing too complex... However, the issue is that the file can be hand edited, so spacing at the beginning and in between each piece can be variable...

Any idea on the sed syntax needed to search for a variable and replace its value?

Many thanks,
 
I don't know much about sed, but I tried it.
sed -E 's/((^|[[:space:]]+)variable[[:space:]]*=[[:space:]]*)[^[:space:]]+/\1value/' filename
Does it work?
 
I don't know much about sed, but I tried it.
sed -E 's/((^|[[:space:]]+)variable[[:space:]]*=[[:space:]]*)[^[:space:]]+/\1value/' filename
Does it work?
Unfortunately, that does not seem to work... Here is my script so far.

Bash:
#!/bin/sh
total_memory=$( sysctl -n hw.physmem | awk '{ byte =$1 /1024/1024/1024; print byte }' )
echo $total_memory
quarter_memory=$(printf "%.0fGB" $(echo $total_memory*.25 | bc))
echo $quarter_memory
#sed -i '' -E "s/\s\(shared_buffers\s=.*$/shared_buffers = $quarter_memory/g" ./postgresql.conf
sed -i '' 's/((^|[[:space:]]+)shared_buffers[[:space:]]*=[[:space:]]*)[^[:space:]]+/\1$quarter_memory/' ./postgresql.conf

I end up getting the following error:

Bash:
sed: 1: "s/((^|[[:space:]]+)shar ...": \1 not defined in the RE
 
sed -E -e "s/((^|[[:space:]]+)shared_buffers[[:space:]]*=[[:space:]]*)[^[:space:]]+/\1\\$quarter_memory/" -i '' ./postgresql.conf
Use -E option.

Edit: -e added.
 
I usually practice a sed command on something where it's easy to see the result - and doesn't mess up the config file. Helped me a LOT.
 
sed -E "s/((^|[[:space:]]+)shared_buffers[[:space:]]*=[[:space:]]*)[^[:space:]]+/\1\\$quarter_memory/" -i '' ./postgresql.conf
Use -E option.
Using the -E option does work and the variable is replaced; however, the replacement is only shown on the screen. The file is not actually modified...
 
Just as an aside, you might want to go to Edit thread (on the right of your first post next to Watch) and mark it as Solved
 
Probably a bit shorter and easier to read selecting the line by the name, something like
sed -i '' -e '/^variable/s/=[^#]*/= $value /'
 
Back
Top