[英]Feed CSV file into variable in Bash for parsing
For each row in a CSV file, I'd like to extract a field and reposition it in the row using Bash. The row is a URL and I am using /
as a delimiter.对于 CSV 文件中的每一行,我想提取一个字段并使用 Bash 将其重新定位在行中。该行是 URL,我使用
/
作为分隔符。
This is the starting file (start.csv):这是起始文件 (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
For later reference, the URL is https://{url}/{version}/irrelevant/{guide}/irrelevant.html
.供以后参考,URL 是
https://{url}/{version}/irrelevant/{guide}/irrelevant.html
。
The desired output is (end.csv):所需的 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
I've unsuccessfully tried many variations of:我试过很多变体都没有成功:
file="start.csv"
var="$(<<<"${file}" cut -d'/' -f4)"
sed -e "s|$|,$var,,,,0|g" < start.csv > end.csv
However this successfully produces a column with the version:然而,这成功地产生了一个版本的列:
cut -d'/' -f4 < start.csv
Somewhere my logic is seriously flawed.我的逻辑在某处存在严重缺陷。 Is anyone able to help me spot my problem?
有人能帮我发现我的问题吗? Thank you.
谢谢你。
It is easier, using awk
:使用
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.