Write to csv file

我的未来我决定 提交于 2021-02-19 06:45:06

问题


I need some contents to be written in csv format to a file using ansible

shell: ps -ef | grep java | awk '{print $1}'
register: username

shell: ps -ef | grep java | awk '{print $2}'
register: id

The output for username will be similar to :

root
admin
test_admin

The output for id will be similar to:

1232
4343
2233

so I want this to be written to a csv file as

root,1232
admin,4343
test_admin,2233

Please suggest.


回答1:


You can use a combination of the zip, map and join filters to achieve your desired result:

- hosts: all
  tasks:
    - name: combination of two lists
      set_fact:
        lines: "{{ [1,2,3]|zip(['a','b','c'])|list }}"
    - debug:
        msg: "{{ lines }}"
    - name: transform each line into a string
      set_fact:
        lines: "{{ lines | map('join', ', ') | list }}"
    - debug:
        msg: "{{ lines }}"
    - name: combine lines
      set_fact:
        lines: "{{ lines | join('\n') }}"
    - debug:
        msg: "{{ lines }}"
    - name: write lines to file
      copy:
        content: "{{ lines }}"
        dest: "output.csv"

Or when you combine the filters together:

- name: write lines to file
  copy:
    content: "{{ [1,2,3] | zip(['a','b','c']) | map('join', ', ')  | join('\n') }}"
    dest: "output.csv"

The content of output.csv will be:

1, a
2, b
3, c


来源:https://stackoverflow.com/questions/56363366/write-to-csv-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!