gpt4 book ai didi

linux - 在 bash 中读取 CSV 文件

转载 作者:太空狗 更新时间:2023-10-29 11:46:13 37 4
gpt4 key购买 nike

我需要在 shell 中读取 CSV 文件,我同意 CSV 文件在一个单元格中只有一行。但是,如果我们在 CSV 文件的单元格中有多行,那么我将无法分隔 CSV 文件。

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

我将从用户那里获取 CSV 文件中的输入,并且必须将给定的行添加到提到的文件中。这里有一个 CSV 文件的每个单元格中有多行,如果我尝试 cat 该文件,它会以不同的顺序给出。

[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"

有什么方法可以让我们从那个文件中读取多行并且行数始终不相同。

最佳答案

这可能是您想要的:

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

如果您花更多时间手动打击,很可能会压缩替代操作。这是一个脆弱的解决方案(大多数不使用专门处理 CSV 格式的代码的解决方案都是脆弱的);如果逗号出现在任何引号括起的字段中,它就会严重失败。

应用于您的数据,它产生:

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

可靠地操作 CSV 格式数据的其他可能工具包括:

如果这不是您要查找的内容,请澄清问题。

关于linux - 在 bash 中读取 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12783324/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com