Venu
Venu

Reputation: 1772

Replace content in a file or line matching a regular expression using SED

How to replace a line / part of a line in a file using SED command?

search_text_1_server=value.env_1.path_to_file
search_text_2_server=value.env_1.path_to_file
search_text_3_server=value.env_1.path_to_file
some_other_key=value.env_1.another_path

Now I want a sed command to find the lines which match the regular expression search_text_{any}_server and then replace env_1 with env_2

Found the regular expression to find the required lines.

^search_text_[a-z_]\*_server.*$

Now how to add the SED syntax to replace

PS : I am not an expert in shell

Upvotes: 0

Views: 2200

Answers (2)

anubhava
anubhava

Reputation: 784928

Your regex is close. You can use:

sed -E 's/^(search_text_[a-z_]*_server=.*)env_1\./\1env_2\./' file

search_text_1_server=value.env_2.path_to_file
search_text_2_server=value.env_2.path_to_file
search_text_3_server=value.env_2.path_to_file
some_other_key=value.env_1.another_path

Upvotes: 1

sjsam
sjsam

Reputation: 21955

Assuming country code to be two alphabets, you could do

sed -Ei 's/(search_text_[a-z]{2}_server=value\.)env_1/\1env_2/' file

should do it.


What's happening here

  1. [a-z]{2} checks for two alphabets which make a country code
  2. sed s command is for substitution -> s/pattern/replacement
  3. () selects the matched regex pattern for reuse, Note \1 for reuse
  4. -i is the inplace edit option of sed which makes changes permanent in the file

Upvotes: 0

Related Questions