Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace string in a file if line starts with another string

How can I replace a string in a file if line starts with another string using sed?

For example, replace this line:

connection = sqlite://keystone:[YOURPASSWORD]@[YOURIP]/keystone

With this line:

connection = mysql://keystone:[email protected]/keystone
like image 417
BlackBeret Avatar asked Jan 10 '13 16:01

BlackBeret


People also ask

Which function replace a given string with another string?

replace(). This replace function replaces only the first occurrence of the match. To do it for all we have used loop. This replace function takes the index from where it will replace, it takes the length of the string, and the string which will be placed in the place of matched string.

How do you replace a string in a line in Python?

replace() is an inbuilt function in the Python programming language that returns a copy of the string where all occurrences of a substring are replaced with another substring. Parameters : old – old substring you want to replace. new – new substring which would replace the old substring.


Video Answer


2 Answers

Answer:

sed '/^start_string/s/search_string/replace_string/'

Information at http://www.gnu.org/software/sed/manual/sed.html#Addresses

like image 129
anishsane Avatar answered Nov 04 '22 15:11

anishsane


You can do simply this :

sed -ri 's/sqlite/mysql/g' YOURFILE
like image 33
kbekkouche Avatar answered Nov 04 '22 15:11

kbekkouche