繁体   English   中英

将 CSV 文件送入 Bash 中的变量进行解析

[英]Feed CSV file into variable in Bash for parsing

对于 CSV 文件中的每一行,我想提取一个字段并使用 Bash 将其重新定位在行中。该行是 URL,我使用/作为分隔符。

这是起始文件 (start.csv):

https://docs.website.com/12-3/articles/guide-1/article-1.html
https://docs.website.com/12-2/articles/guide-2/article-5.html
https://docs.website.com/12-1/articles/guide-3/article-6.html

供以后参考,URL 是https://{url}/{version}/irrelevant/{guide}/irrelevant.html

所需的 output 是 (end.csv):

url,name,tag,version,guide,views
https://docs.website.com/12-3/articles/guide-1/article-1.html,,,12-3,guide-1,0
https://docs.website.com/12-2/articles/guide-2/article-5.html,,,12-2,guide-2,0
https://docs.website.com/12-1/articles/guide-3/article-6.html,,,12-1,guide-3,0

我试过很多变体都没有成功:

file="start.csv"
var="$(<<<"${file}" cut -d'/' -f4)"

sed -e "s|$|,$var,,,,0|g" < start.csv > end.csv

然而,这成功地产生了一个版本的列:

cut -d'/' -f4 < start.csv

我的逻辑在某处存在严重缺陷。 有人能帮我发现我的问题吗? 谢谢你。

使用awk更容易:

awk -F/ -v OFS=, '{print $0, "", "", $4, $6, 0}' file

https://docs.website.com/12-3/articles/guide-1/article-1.html,,,12-3,guide-1,0
https://docs.website.com/12-2/articles/guide-2/article-5.html,,,12-2,guide-2,0
https://docs.website.com/12-1/articles/guide-3/article-6.html,,,12-1,guide-3,0

暂无
暂无

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

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