Ignore sed string starting with regex

I am trying to replace properties in a properties file using sed in a shell script; the command below works great

sed "s!${KEY}=.*!${KEY}=${NEWVAL}!" infile > outfile 

Problem - this guy is also replacing the corresponding "KEY" in the comments.

file example:

 ########### #ws.clients=http://abc123.com ws.clients=http://123.com ########### 

script:

 #!/bin/ksh KEY="ws.clients" NEWVAL="http://abcd.com" sed "s!${KEY}=.*!${KEY}=${NEWVAL}!" infile > outfile 

exit:

 ########### #ws.clients=http://abcd.com ws.clients=http://abcd.com ########### 

I tried several ways, but could not escape the line starting with "#" ... sentences?

+4
source share
2 answers

You can add a condition to the replace statement:

 sed "/^[^#]/ s!${KEY}=.*!${KEY}=${NEWVAL}!" infile > outfile 

/^[^#]/ reads as "everything except the pound sign at the beginning of the line."

+5
source

You can do it as follows:

 sed "s!^${KEY}=.*!${KEY}=${NEWVAL}!" infile > outfile 

Just added ^ to match only those that start at the beginning of the line. Well, above ans, you also need to work, but they will have the same problem if your line starts with space .

0
source

Source: https://habr.com/ru/post/1402353/


All Articles