写入csv文件 [英] Write to csv file
本文介绍了写入csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用ansible将csv格式的某些内容写入文件中
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
id的输出将类似于:
The output for id will be similar to:
1232
4343
2233
所以我希望将其写为csv文件
so I want this to be written to a csv file as
root,1232
admin,4343
test_admin,2233
请提出建议.
推荐答案
您可以结合使用zip,map和join过滤器来实现所需的结果:
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"
output.csv的内容为:
The content of output.csv will be:
1, a
2, b
3, c
这篇关于写入csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文