写入 .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
用户名的输出类似于:
root
admin
test_admin
id 的输出类似于:
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屋!
查看全文