Generally to use sed, we would do;
sed -i 's/old-text/new-text/g' file.txt
where file.txt is the file containing old-text and new-text.
If we want to ensure that our search term is at the beginning of the line, we add the ^ as follows;
sed -i 's/^old-text/new-text/g' file.txt
A problem I found though was that I wanted to use this inside of a bash file and use variables but found that the variable, example $TEMP_VARIABLE would not be expanded to what the actual variable was and to get around this, I had to use double quotes and escape any double quote that I wanted to be part of the search or replace term, so;
where the search term was MASTER_IP="some text", here we used .* as a wild card so the search term was everything after the MASTER_IP="
so MASTER_IP=\".*
the replacement term was "MASTER_IP="new text" and for this we used the $TEMP_VARIABLE and also escaped the first and last double quote.
so MASTER_IP=\"$TEMP_VARIABLE\"
The $SQL_PATH$APP_NAME are variables for the path/file which in this case was actually the same file containing the sed command. So we were essentially running a bash script to change it's own variables. This is particularly useful if we have a script that has custom variables for each server etc and yet we want to allow updating of the file with the most recent versions, as is the case with my script-buddy. Until now, I would have to download the latest version of the file and then modify any variables specific to the target server or whatever customisation was required. An extract of the functions from my sql wrapper are below;
Assuming TEMP_VARIABLE has been declared earlier, calling the change_ip_and_ports function would in this case allow the changing of 4 variables within the file, MASTER_IP, SLAVE_IP, MASTER_PORT and SLAVE_PORT (again assuming they have been declaired earlier).
No comments:
Post a Comment
Note: only a member of this blog may post a comment.