I want to use the raw module to run a 'sed' command which will contain escape characters.

- name: Search for prefix in file and replace all following text with addition
  raw: "sed 's/\({{ prefix }}\)\(.*\)/\1 {{ addition }}/g' {{ file }} > {{ file }}.test"

This, however complains with:

ERROR! Syntax Error while loading YAML.
found unknown escape character

With the '^' pointing at the first '\' in the string. How to I include escape characters in this command without ansible trying to process them?


The task below works

- raw: 'sed --regexp-extended ''s/({{ prefix }})(.*)/\1 {{ addition }}/g'' {{ file }} > {{ file }}.test'

with variables

file: test
prefix: AAA
addition: XXX


$ cat test
alsdjflaskdjfasn AAA fasdfasdfsadf

$ cat test.test 
alsdjflaskdjfasn AAA XXX

Modified regex from "^" till "$"

- raw: 'sed --regexp-extended ''s/^(.*)({{ prefix }})(.*)$/\1 {{ addition }}/g'' {{ file }} > {{ file }}.test2'


$ cat test.test2
alsdjflaskdjfasn  XXX


| improve this answer | |
  • Hi, this answer is great and worked, but could you explain the quotes, and why my quotes were incorrect? – JBansible Jul 22 '19 at 12:02
  • Also in the second example, i think you're missing a '\2' after the '\1' to include the prefix – JBansible Jul 22 '19 at 12:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.