大网数据广告活动
服务器运维问答

Ansible split string on backslash

· 52CE 我爱测

I'm passing a list of dir/subdirs into a playbook as follows: dirs=['Web\this','Web\that','Web'] This works fine when I actually do tasks on those directories (win_shell, invoking a build process), but later I need to copy the fi…

问题原文

原帖链接 · Wolske · CC BY-SA 4.0

I'm passing a list of dir/subdirs into a playbook as follows:

dirs=['Web\this','Web\that','Web']

This works fine when I actually do tasks on those directories (win_shell, invoking a build process), but later I need to copy the files and the '\' does not work when used as part of a filename. I'm interested in using the following, so I'll get the module name for most builds and 'Web' for the one that is in the root folder:

dirs[1].split('\\')[-1]

I hoped this would return 'this', 'that', and 'Web', respectively.

But I can't find any combination of slashes or regex magic to split my strings. I've found about 5 questions/answers in StackExchange that are close, but none of them seem to do it.

I've also tried this with variations of

"{{ dirs[1] | regex_replace('\\','-') }}"

已采纳解答

原帖链接 · Vladimir Botka · CC BY-SA 4.0

Declare a variable with the separator to avoid the quotation&escaping alchemy. Use Single-Quoted Style; backslash '\' can be used freely. For example, the task below

  - debug:
      msg: "{{ dirs[1].split(separator)[-1] }}"
    vars:
      separator: '\'
      dirs: ['Web\this','Web\that','Web']

gives

  msg: that

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2019-09-27)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。