0

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} 
2
  • Do you want the commas in the data or not? 3 of the 4 values in the hypothetical syntax have a comma after them, which might or might not be the comma in the data. Commented Dec 2, 2015 at 21:58
  • No I don't want the commas Commented Dec 2, 2015 at 22:04

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is great if I was just making the directories, but I want the loop because I need to do other things with the variable.
0
$ 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.