如何将字符串追加到文件中第一次出现的行的末尾

问题描述 投票:0回答:1
If a file is having below content

Label abc
First line
Second line
Append line at the end of this line
Append line at the end of this line
Append line at the end of this line
Last line

How to append a string “added string” to the first occurrence of “Append line at the end of this line” using ansible playbook 

Label abc
First line
Second line
Append line at the end of this line added string 
Append line at the end of this line
Append line at the end of this line
Last line

我厌倦了下面的内容,但整个文件内容都被修改了

- name: Replace only the first occurrence of a line in a file and append values
  hosts: localhost
  tasks:
    - name: Read the file content
      slurp:
        path: /path/to/your/file
      register: file_content

    - name: Modify only the first occurrence of the line and append values
      set_fact:
        updated_lines: >-
          {%- set found = False -%}
          {%- for line in (file_content.content | b64decode).split('\n') -%}
            {%- if not found and line.startswith('label Linux') -%}
              {%- set found = True -%}
              {{ line + ' your_append_text' }}
            {%- else -%}
              {{ line }}
            {%- endif -%}
          {%- endfor -%}

    - name: Write the modified content back to the file
      copy:
        content: "{{ updated_lines | join('\n') }}"
        dest: /path/to/your/file
        backup: yes
ansible jinja2 ansible-2.x
1个回答
0
投票

给定文件

shell> cat /tmp/ansible/file 
Label abc
First line
Second line
Append line at the end of this line added string
Append line at the end of this line
Append line at the end of this line
Last line

以下任务可以满足您的要求

    - lineinfile:
        path: /tmp/ansible/file
        regexp: '^Append line at the end of this line.*$'
        line: 'Append line at the end of this line added string'
        firstmatch: true

给予

shell> cat /tmp/ansible/file 
Label abc
First line
Second line
Append line at the end of this line added string
Append line at the end of this line
Append line at the end of this line

任务是幂等的。

© www.soinside.com 2019 - 2024. All rights reserved.