Ansible| Shell: How to store a variable for each line from text.txt and put them after each line with {value +1}

Viewed 43

I need to duplicate the values and put them into the file after each line with value +1. The file I will receive will not be like this every time, so I'll need to store every value to variable.

text.txt

12345
12346
12347
12348
12349

Result I want

12345 12346
12346 12347
12347 12348
12348 12349

How can I do this with Ansible or shell command?

1 Answers

For example, given the file

shell> cat /tmp/text.txt 
12345
12346
12347
12348
12349

Read the file and create the block

    - command: cat /tmp/text.txt
      register: result
    - debug:
        msg: |-
          {% for i in result.stdout_lines %}
          {{ i }} {{ i|int + 1 }}
          {% endfor %}

gives

  msg: |-
    12345 12346
    12346 12347
    12347 12348
    12348 12349
    12349 12350

Write the block into a file if you want to

    - copy:
        dest: /tmp/text2.txt
        content: |-
          {% for i in result.stdout_lines %}
          {{ i }} {{ i|int + 1 }}
          {% endfor %}

gives

shell> cat /tmp/text2.txt 
12345 12346
12346 12347
12347 12348
12348 12349
12349 12350

Example of a complete playbook

- hosts: localhost
  tasks:
    - command: cat /tmp/text.txt
      register: result
    - debug:
        msg: |-
          {% for i in result.stdout_lines %}
          {{ i }} {{ i|int + 1 }}
          {% endfor %}
    - copy:
        dest: /tmp/text2.txt
        content: |-
          {% for i in result.stdout_lines %}
          {{ i }} {{ i|int + 1 }}
          {% endfor %}
Related