如何使用Miller将CSV文件的每个字段单独逐行输出?
关于Miller工具直接展开CSV字段的问题
原始CSV文件内容
cat file "Field 1, Line 1",Field 2,"Field 3, Line 1" "Field 1, Line 2",Field 2,"Field 3, Line 2"
期望输出格式
"Field 1, Line 1" "Field 2" "Field 3, Line 1" "Field 1, Line 2" "Field 2" "Field 3, Line 2"
尝试过的命令及问题
尝试用以下Miller命令实现,但未产生任何输出:
mlr --csv -N --ofs lf --quote-all cat file
现有替代方案
- 结合Miller与sed实现:
mlr --csv -N --ofs pipe --quote-all cat file | sed 's/"|"/"\n"/g'
- 使用Ruby命令实现:
ruby -r csv -e 'CSV.parse($<.read).flatten.each{|r| puts [r].to_csv(force_quotes: true)}' file
Miller原生解决方案
Miller本身支持直接实现这种逐个输出字段的需求,无需依赖外部工具。可以通过flatten函数将每条记录的字段展开为单独条目,再配合输出参数即可:
mlr --csv -N --quote-all flatten -r ".*" then cat file
命令说明
-N:指定CSV文件无表头flatten -r ".*":匹配所有字段,将每条记录的多个字段展开为独立的单行条目--quote-all:强制所有输出字段带双引号then cat:输出处理后的内容
执行该命令后,即可直接得到你期望的逐行字段输出。
内容的提问来源于stack exchange,提问作者dawg
相关产品推荐
相关产品推荐

