dsaydon
dsaydon

Reputation: 4769

ansible regex_replace filter forward slash

I'm trying to use regex replace filter in order to extract all the string from start till the last forward slash

this from linux with sed is working:

echo /a/b/c.log |  sed 's/\(.*\)\/.*/\1/'
output: /a/b

but using ansible:

"{{log_path | regex_replace('s/\(.*\)\/.*/\', '1/')}}"

Remark: log_path is a var that has log full path like /a/b/c.log

i'm getting errors such as:

exception: while parsing a quoted scalar

found unknown escape character

I know that i can do somthing like that : "{{log_path.split('/')[0:-1] | join('/')}}"

but I prefer with regex

any idea what I'm doing wrong?

Upvotes: 1

Views: 5726

Answers (1)

erik258
erik258

Reputation: 16275

Don't use sed syntax (s/pattern/replacement/ ) for ansible. Just put the regular expression right into the string. You also don't need to escape () parentheses. I don't think you'll need to escape slashes either. In fact, the PCRE of Python/ansible differs significantly from their predecessors. I'm a lover of sed, but I'd recommend you develop your regular expressions for ansible in Python, not sed.

Actually, your problem isn't any of those, though they would make the pattern wrong. Your issue is that you're escaping the closing single quote. Hard to see though, with all those back slashes .

This should get you started in the right direction:

"{{log_path | regex_replace('(.*)/.*/', '\1')}}"

http://docs.ansible.com/ansible/latest/replace_module.html has more examples towards the bottom.

Upvotes: 1

Related Questions