Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use sed to change my configuration files, with flexible keys and values?

Tags:

linux

bash

sed

I want to search a configuration file for this expression: "central.database". I then want to change the setting associated with "central.database" to "SQLTEST".

The layout of the config file would look like this initially:

central.database = SQLFIRSTTEST 

This is what i want it to look like after the sed replacement:

central.database = SQLTEST 

I am doing this in a bash script, any suggestions, recommendations or alternative solutions are welcome!

(Actually both central.database and SQLTEST come from bash variables here.)


My current code (third attempt):

sshRetValue=$(ssh -p "35903" -i $HOME/sshids/idrsa-1.old ${1} <<EOF         sed -i "s/^\($CENTRAL_DB_NAME\s*=\s*\).*\$/\1$CENTRAL_DB_VALUE/" /home/testing.txt;         echo $? EOF ) 

Error message:

Pseudo-terminal will not be allocated because stdin is not a terminal. sed: -e expression #1, char 58: unknown option to `s' -bash: line 3: EOF: command not found 
like image 678
prolink007 Avatar asked May 10 '11 19:05

prolink007


People also ask

How do you replace a variable in a file using sed?

How SED Works. In the syntax, you only need to provide a suitable “new string” name that you want to be placed with the “old string”. Of course, the old string name needs to be entered as well. Then, provide the file name in the place of “file_name” from where the old string will be found and replaced.

Can you use sed on multiple files?

Here is a quick command that you can use to search and replace a piece of text across multiple files using find, xargs, and sed.


1 Answers

sed -i -e '/central\.database =/ s/= .*/= new_value/' /path/to/file 

Explanation:

  • -i tells sed to save the results to the input file. Without it sed will print the results to stdout.
  • /central\.database =/ matches lines that contain the string between slashes: central.database =. The . is escaped since it's a special character in regex.
  • The s/OLD/NEW/ part performs a substitution. The OLD string is a regular expression to match and the NEW part is the string to substitute in.
  • In regular expressions, .* means "match anything". So = .* matches an equal sign, space, and then anything else afterward.
like image 135
John Kugelman Avatar answered Sep 25 '22 16:09

John Kugelman