使用Ansible仅删除文件中第一个出现的行

时间:2017-04-19 17:49:02

标签: linux shell sed ansible

我正在使用ansible v2.2.1,我只需删除文件中第一次出现的行。所以我的ansible剧本如下。

---   
- hosts: localhost
  tasks:
  - name: read file content
    command: cat occurence.txt
    register: fc
  - debug: var=fc

  - debug: msg="{{ item }}"
    with_items:
     - "{{ fc.stdout_lines }}"

  - name: first occurence in file
    shell: sed -i '0,/{{ item }}/{/{{ item }}/d;}' occurence.txt
    with_items:
     - "{{ fc.stdout_lines }}"
    register: remove
  - debug: var=remove

occurence.txt 文件包含以下内容

this is apple
this is apple
this is banana
this is apple
this is orange

如何只删除第一次出现的"这是apple"并留下其余的线?

3 个答案:

答案 0 :(得分:1)

查找行,当找到替换为(最初为空)保留空间时 对于以后出现的情况,交换到相同的保持空间将基本上打印未更改的行,即使它严格来说,它是前一个相同的行。
如果(仅第一个)空行来自保留空间,则删除。

sed "/^this is apple$/{x;/^$/d}"

答案 1 :(得分:1)

我喜欢Yunnosch对这个问题的解释。另一种选择是:

sed '0,/^this is apple$/{//d}'

从文件的开头到第一次出现的apple行,只删除与上一个匹配项匹配的行。

答案 2 :(得分:0)

我使用set_fact变量解决了以下问题。

---

- hosts: localhost

  tasks:

  - name: read file content
    command: cat occurence.txt
    register: fc
  - debug: var=fc

  - debug: msg="{{ item }}"
    with_items:
     - "{{ fc.stdout_lines }}"

  - set_fact: value="this is apple"
  - debug: var=value

  - name: first occurrence in file
    shell: sed -i '0,/{{ value }}/{/{{ value }}/d;}' occurence.txt
    register: remove
  - debug: var=remove 
相关问题