anamaria
anamaria

Reputation: 362

Write to file from within a for loop in Bash

Let's say I have the following csv file:

A,1
A,2
B,3
C,4
C,5

And for each unique value i in the first column of the file I want to write a script that does some processing using this value. I go about doing it this way:

CSVFILE=path/to/csv
VALUES=$(cut -d, -f1 $CSVFILE | sort | uniq)

for i in $VALUES;
do
cat >> file_${i}.sh <<-!
#!/bin/bash
#
# script that takes value I
#
echo "Processing" $i
!
done

However, this creates empty files for all values of i it is looping over, and prints the actual content of files to the console.

Is there a way to redirect the output to the files instead?

Upvotes: 1

Views: 10261

Answers (2)

Akhil
Akhil

Reputation: 1040

Simply

#!/bin/bash

FILE=/path/to/file

values=`cat $FILE | awk -F, '{print $1}' | sort | uniq | tr '\n' ' '`

for i in $values; do
 echo "value of i is $i" >> file_$i.sh
done

Screenshot

scrot

Upvotes: 3

mickp
mickp

Reputation: 1809

Try using this:

#!/usr/bin/env bash    

csv=/path/to/file

while IFS= read -r i; do
cat >> "file_$i.sh" <<-eof
#!/bin/bash
#
# Script that takes value $i ...
#
eof
done < <(cut -d, -f1 "$csv" | sort -u)

Upvotes: 0

Related Questions