9

I have a CSV file like:

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

And I have a command that take this parameters:

./mycommand --name="Daniel Dvorkin" --age=28 --address="Some Address St. 1234"

What is the easiest way to run mycommand for each line of the CSV?

MZAweb
  • 553

3 Answers3

8

That's pretty easy:

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

1d will delete caption line. s command will modify the string like in your example e in the end of s command will execute the string. this is GNU extension, so if you don't have GNU sed, you can use xargs instead e:

sed '1d;s/\([^,]*\),\([^,]*\),\([^,]*\)/.\/mycommand --name="\1" --age="\2" --address="\3"/' file.csv | xargs
rush
  • 27,403
6

If your CSV is simple CSV with no quoting mechanism (hence commas cannot appear in a field), you can do the parsing in the 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

If fields can be quoted, you need a real CSV parser. Use Perl, Python, R, Ruby or other languages.

2

Besides sed, there is awk...

awk -F, 'NR > 1 { system("./mycommand --name=\\\"" $1 "\\\" --age=" $2 " --address=\\\"" $3 "\\\"") }' < file.csv
L2G
  • 121