user2483176
user2483176

Reputation: 317

read in column from csv file into bash script

In a bash script I want to loop over values I have stored in a csv file. How can I import a column from a csv file into a bash script and then do something like:

for i in {column imported from csv}

do
mkdir "$i"
done

my csv file looks like this:

1, 3, 8
4, 6, 10
123, 6, 8
324, 9, 12

how do I import the first column to get:

for i in {1, 4, 123, 324} 

Upvotes: 0

Views: 3886

Answers (2)

anubhava
anubhava

Reputation: 785876

You don't even need to loop, just use cut with xargs:

cut -d, -f1 file | xargs mkdir

To get the first column using a for loop:

while IFS=, read -ra arr; do
   echo "processing ${arr[0]}"
done < file
processing 1
processing 4
processing 123
processing 324

Change echo to whatever command you want to use inside the loop.

Upvotes: 3

karakfa
karakfa

Reputation: 67547

$ for i in $(cut -d, -f1 file); do mkdir "$i"; ... ; done

or replace cut with awk

$ for i in $(awk -F, '{print $1}' file); do mkdir "$i"; ... ; done

Upvotes: 0

Related Questions