简体   繁体   English

在bash中读取CSV文件

[英]Read a CSV file in bash

I have a requirement to read the CSV file in shell, Well I am ok with the CSV file having single line in a cell. 我需要在外壳中读取CSV文件,我可以在单元格中只有一行的CSV文件中使用该文件。 But if we have multiple lines in cell of CSV file then I am unable to delimit the the CSV file. 但是,如果我们在CSV文件的单元格中有多行,那么我将无法分隔CSV文件。

Filename            Lines
/etc/hosts          example.test.com
                    example2.test.com
/etc/resolv.conf    nameserver dns.test.com
                    search test.com

I will take input from the user in a CSV file and have to add the given lines to the mentioned files. 我将从CSV文件中接收用户的输入,并且必须将给定的行添加到提到的文件中。 Here there are multiple lines in each cell of a CSV file and If I try to cat the file it is giving in a different order. 此处CSV文件的每个单元格中都有多行,如果我尝试显示该文件,则该文件将以不同的顺序给出。

[user2@mon ~]$ cat test2.csv
"Filename","Lines"
"/etc/hosts","example.test.com"
,"example2.test.com"
"/etc/resolv.conf","nameserver dns.test.com"
,"search test.com"

Is there any way we can read the multiple lines from that file and number of lines is not same in all the time. 有什么办法可以从该文件中读取多行,并且行数总是不一样。

This might be what you're after: 这可能是您想要的:

awk -F, '{ sub(/^"/, "", $1); sub(/"$/, "", $1);
           sub(/^"/, "", $2); sub(/"$/, "", $2);
           printf "%-20s  %s\n", $1, $2;
         }'

It may well be possible to compress the substitute operations if you spend more time manual bashing. 如果您花费更多时间进行手动扑打,很有可能会压缩替代操作。 This is fragile as a solution (most solutions not using code specialized for dealing with CSV format are fragile); 这是一个脆弱的解决方案(大多数未使用专门用于处理CSV格式的代码的解决方案都是脆弱的); it fails horribly if a comma appears inside any of the quote-enclosed fields. 如果在任何用引号引起来的字段中出现逗号,则将严重失败。

Applied to your data, it yields: 应用于您的数据,它会产生:

Filename              Lines
/etc/hosts            example.test.com
                      example2.test.com
/etc/resolv.conf      nameserver dns.test.com
                      search test.com

Other possible tools to manipulate CSV format data reliably include: 其他可靠地处理CSV格式数据的工具包括:

If this is not what you are looking for, please clarify the question. 如果这不是您想要的内容,请阐明问题。

假设您的输入与您的示例一样基本,那么您也许可以通过以下操作而摆脱:

sed 's/^,/ ,/' test2.csv | tr -d \" | column -s, -t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM