如何使用 regexp 从文件中的字符串行中提取第一组/一组数字并忽略行有两组数字、任何符号(PASS_MAX_DAYS 除外),并显示在终端上。我没有对文件(login.defs)进行任何修改。
示例(仅粗体数字)
PASS_MAX_DAYS30
PASS_MAX_DAYS 30 .12(忽略)
PASS_MAX_DAYS $30(忽略)
PASS_MAX_DAYS 30 23(忽略)
PASS_MAX_DAYS 30 天(忽略)
PASS_MAX_@第 30 天(忽略)
- name: extract num from pass max days
hosts: localhost
tasks:
- lineinfile:
path: /etc/login.defs
state: absent
regexp: '(?i)^\s*PASS_MAX_DAYS\s+[0-9]+\s*$'
check_mode: yes
register: days
- name: show password max days
debug:
msg: "{{days}}" #Show max days
when: days <= 90
答案1
给定文件
shell> cat /tmp/login.defs
PASS_MAX_DAYS 30
PASS_MAX_DAYS 30 .12
PASS_MAX_DAYS $30
PASS_MAX_DAYS 30 23
PASS_MAX_DAYS 30 days
PASS_MAX_@DAYS 30
读取文件
- command: cat /tmp/login.defs
register: out
例如,将下面的声明放入 playbook 变量中
regexp: '(?i)^\s*PASS_MAX_DAYS\s+[0-9]+\s*$'
pass_max_days: "{{ out.stdout_lines|
select('match', regexp)|first|split|last }}"
给出
pass_max_days: '30'
用于测试的完整剧本示例
- hosts: localhost
vars:
regexp: '(?i)^\s*PASS_MAX_DAYS\s+[0-9]+\s*$'
pass_max_days: "{{ out.stdout_lines|
select('match', regexp)|first|split|last }}"
tasks:
- command: cat /tmp/login.defs
register: out
- debug:
var: pass_max_days
问:“如何用日子来比较?”
A:将其转换为整数。例如
- debug:
msg: Less than 90 days
when: pass_max_days|int < 90
- debug:
msg: Exactly 90 days
when: pass_max_days|int == 90
- debug:
msg: More than 90 days
when: pass_max_days|int > 90
给
TASK [debug] *******************************************************
ok: [localhost] =>
msg: Less than 90 days
TASK [debug] *******************************************************
skipping: [localhost]
TASK [debug] *******************************************************
skipping: [localhost]