在Ansible中,您可以使用regex_search
过滤器和正则表达式来匹配字符串并提取行。以下是一个示例解决方法:
假设您有一个名为file.txt
的文本文件,内容如下:
This is line 1
This is line 2
This is line 3
您可以使用以下Ansible任务来匹配包含特定字符串的行并提取它们:
- name: Match and extract lines using regex
hosts: localhost
gather_facts: false
tasks:
- name: Read file content
shell: cat file.txt
register: file_content
- name: Match and extract lines
set_fact:
matched_lines: "{{ file_content.stdout_lines | regex_search('.*line \\d+') }}"
- name: Print matched lines
debug:
var: matched_lines
在上面的示例中,我们首先使用shell
模块读取文件的内容,并使用register
选项将输出存储在file_content
变量中。
然后,我们使用regex_search
过滤器和正则表达式.line \\d+
来匹配包含字符串line
和一个或多个数字的行,并将匹配的行存储在matched_lines
变量中。
最后,我们使用debug
模块打印出匹配的行。
当您运行此Playbook时,您将看到输出如下:
TASK [Print matched lines] ****************************************************************
ok: [localhost] => {
"matched_lines": [
"This is line 1",
"This is line 2",
"This is line 3"
]
}
正如您可以看到的,匹配的行已经被提取出来并存储在matched_lines
变量中。