使用 CSV 行作为命令参数

MZA*_*web 9 shell pipe text-processing csv

我有一个 CSV 文件,如:

Name,Age,Address
Daniel Dvorkin,28,Some Address St. 1234
(... N ...)
Foo Bar,90,Other Address Av. 3210
Run Code Online (Sandbox Code Playgroud)

我有一个带这个参数的命令:

./mycommand --name="Daniel Dvorkin" --age=28 --address="Some Address St. 1234"
Run Code Online (Sandbox Code Playgroud)

为 CSV 的每一行运行mycommand的最简单方法是什么?

rus*_*ush 8

这很简单:

sed '1d;s/\([^,]*\),\([^,]*\),\([^,]*\)/.\/mycommand --name="\1" --age="\2" --address="\3"/e' file.csv
Run Code Online (Sandbox Code Playgroud)

1d将删除标题行。 scommand 将像您的示例e中那样修改字符串, 在scommand的末尾将执行该字符串。这是GNU扩展,所以如果你没有GNU sed的,你可以使用xargs,而不是e

sed '1d;s/\([^,]*\),\([^,]*\),\([^,]*\)/.\/mycommand --name="\1" --age="\2" --address="\3"/' file.csv | xargs
Run Code Online (Sandbox Code Playgroud)


Gil*_*il' 6

如果您的 CSV 是没有引用机制的简单 CSV(因此逗号不能出现在字段中),您可以在 shell 中进行解析。

{
  read line  # ignore the header line
  IFS=,
  while read -r name age address; do
    ./mycommand --name="$name" --age="$age" --address="$address"
  done
} <input.csv
Run Code Online (Sandbox Code Playgroud)

如果可以引用字段,则需要一个真正的 CSV 解析器。使用Perl、Python、R、Ruby 或其他语言。