regex - Ansible:在变量周围放置引号,但前提是引号尚不存在

标签 regex ansible

我希望将一些文本放在conf 文件中的引号 [1] 中。暂时假设字符串中不包含单引号或双引号:没有 '",

[1] 单引号或双引号在这里都可以使用。为简单起见,下面的所有示例都使用单引号。

之前:

SOMEVARIABLE=string_that_I_want_in_quotes

之后:

SOMEVARIABLE='string_that_I_want_in_quotes'

为此,我使用了替换模块,这是我尝试过的

- name: modify the file again to add quotes to variable
  replace:
    path: "/path/to/file"
    regexp: '^SOMEVARIABLE=(.+)'
    replace: |
      SOMEVARIBLE='\1'

问题在于,在后续运行 ansible 任务时,该变量被封装在第二组单引号中。第三次运行时,会重复此过程。

两 (2) 次 ansible 运行后

SOMEVARIABLE=''string_that_I_want_in_quotes''

三 (3) 次 ansible 运行后

SOMEVARIABLE='''string_that_I_want_in_quotes'''

我怀疑我需要制作一些正则表达式,如果字符串周围已经有单引号,那么它不会以某种方式运行替换。注意:可以检测字符串周围是否有双引号的正则表达式也可以工作。是否有一些正则表达式可以帮助解决这个问题?

注意:我无法生成以字符串开头的引号的文件。相反,该文件是由我无法控制的安装程序自动生成的,并且我正在尝试用引号修改所述安装程序的输出。

最佳答案

使用

- name: modify the file again to add quotes to variable
  replace:
    path: "/path/to/file"
    regexp: "^SOMEVARIABLE='*(.*?)'*$"
    replace: >-
      SOMEVARIABLE='\1'

参见regex proof

说明

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  SOMEVARIABLE=            'SOMEVARIABLE='
--------------------------------------------------------------------------------
  '*                       '\'' (0 or more times (matching the most
                           amount possible))
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    .*?                      any character except \n (0 or more times
                             (matching the least amount possible))
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  '*                       '\'' (0 or more times (matching the most
                           amount possible))
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string

关于regex - Ansible:在变量周围放置引号,但前提是引号尚不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67675542/

相关文章:

php - 从数据中提取 JSON 数组

regex - 替换所有不跟具体的换行符

C# 正则表达式提取包含在单引号中的字符串

ruby-on-rails - rails 电子邮件验证格式和正则表达式

ruby - 我如何使用 gsub 将正则表达式 ruby​​ 替换为第 10 组?

vagrant - 带有 Ansible 的客户机上的别名

当主机无法访问时 ansible 跳过失败模块

ansible - 使用 Ansible 替换字符串中的字符

linux - Ansible 返回码错误 : 'dict object' has no attribute 'rc'

node.js - 通过 bash 使用 npm 在 vagrant guest 上安装 gulp