linux - 使用 Ansible 仅删除文件中第一次出现的行

标签 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

如何只删除第一次出现的“this is apple”行并保留其余行?

最佳答案

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

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

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

关于linux - 使用 Ansible 仅删除文件中第一次出现的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43502772/

相关文章:

java - Linux 上没有默认浏览器的解决方法?

javascript - curl 命令查看从测试程序发送到 Linux 上的网络服务器的消息

linux - 从变量 unix 中提取值

regex - 在 bash 中使用从行的中间或末尾提取单词

linux - 如何使用 sed 在特定行的开头添加文本?

linux - 删除shell中一行的最后一个字

c++ - 无法为我的 LruCache 类定义模板化类型

linux - 未找到 Ubuntu Xenial upstart 服务

javascript - ImageMagick 的批量转换 Shell 脚本

c - dup2 导致程序停止