我希望将一些文本放在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'
说明
--------------------------------------------------------------------------------
^ 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/