BlackBeret
BlackBeret

Reputation: 301

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

Upvotes: 24

Views: 35946

Answers (4)

AstraSerg
AstraSerg

Reputation: 522

If you want to change an entire line which starts with a pattern and ends with enything else, you can use command c description Example

sed -i '/^connection = sqlite/c\connection = mysql://keystone:[email protected]/keystone' your_file

Upvotes: 5

kbekkouche
kbekkouche

Reputation: 49

You can do simply this :

sed -ri 's/sqlite/mysql/g' YOURFILE

Upvotes: 4

alinsoar
alinsoar

Reputation: 15793

sed '/^string1/ { s,string2,string3, }' file

This will replace string2 with string3 on all the lines that start with string1.

Upvotes: 2

anishsane
anishsane

Reputation: 20980

Answer:

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

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

Upvotes: 31

Related Questions