使用 awk 的解决方案:
# begin by reading the whole first template file at once
BEGIN { RS = "^$" }
FILENAME==ARGV[1] { # NR=1 is the entire template file
template = $0
# very conveniently we can now setup RS FPAT etc to apply to the next line for the next file.
RS = "\r\n"
# quoted CSV fields pattern
FPAT = "([^,]*)|(\"[^\"]+\")"
}
FILENAME==ARGV[2] && NR==2 { # NR=2 is the first CSV line: column headers
for (i = 1; i <= NF; i++) {
headers[i] = $i
}
}
FILENAME==ARGV[2] && NR>2 { # NR>2 is the rest of the CSV file records.
# Strip quotes from quoted CSV values.
for (i = 1; i <= NF; i++) {
if (substr($i, 1, 1) == "\"") {
$i = substr($i, 2, length($i) - 2)
}
}
# Template Replacements
result = template
for (i = 1; i <= length(headers); i++) {
gsub(headers[i], $i, result);
}
print result > "svg/" $1 ".svg"
}
这样使用:
awk -f build.awk template.svg employees.csv
其中 template.svg 是一个模板 SVG 文件,其中包含您要替换的字段名称。例如:
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<g>
<title>Layer 1</title>
<rect width="100%" height="100%" fill="blue"/>
<text id="svg_1" y="100" x="76" fill="#FFF">NAME</text>
</g>
</svg>
此模板需要一个具有列标题“NAME”的 CSV 文件,但您可以在模板中添加与 CSV 中一样多的字段。这些文件将在“svg/”目录中输出,每行一个文件。