I have a string in Zabbix agent configuration like
HostMetadata=Linux
I want change it with variable "nginx" to:
HostMetadata=Linux nginx
This changes must be idempotent. But when I am using code twice, line changed to
HostMetadata=Linux nginx nginx
My code:
 - name: regexp
 lineinfile:
 path: /etc/zabbix/zabbix_agentd.conf
 regexp: '^(HostMetadata=Linux.*)$'
 line: '1円 nginx'
 backrefs: yes
 tags: regexp
I tried "^HostMetadata=((?!nginx).)*$", but it breaks next step, and result will be "x nginx"
I want create reusable code and add new parameters. For example:
VAR=nginx
"HostMetadata=Linux" -> "HostMetadata=Linux nginx"
VAR=apache
"HostMetadata=Linux nginx" -> "HostMetadata=Linux nginx apache"
VAR=nginx
"HostMetadata=Linux nginx apache" -> "HostMetadata=Linux nginx apache" (nothing changed)
1 Answer 1
You should only capture the part you need to keep, the rest should be just matched.
You may use
regexp: '^(HostMetadata=Linux).*'
See the regex demo.
Details
- ^- start of string
- (HostMetadata=Linux)- capturing group #1 (referred to with- 1円from the replacement string): the literal string
- .*- the rest of the string to the end, any 0 or more chars other than line break chars, as many as possible.
 answered May 14, 2020 at 9:24
 
 
 
 Wiktor Stribiżew 
 
 631k41 gold badges501 silver badges629 bronze badges
 
 
 Sign up to request clarification or add additional context in comments.
 
 
 
 4 Comments
Alxi Rus
 Thanks for answer. Sorry, this is my first quiestion =) I added more description to question.
  Wiktor Stribiżew
 @AlxiRus So, try 
  ^(HostMetadata=Linux(?!.*nginx).*)Wiktor Stribiżew
 @AlxiRus Is that better?
  Alxi Rus
 Thank you very much! Exactly what I want!
  lang-py