1

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?

5
  • what's your target idea on those values? post what should be the final result Commented Oct 17, 2019 at 11:42
  • 2
    $CSVFILE=path/to/csv is an error. You likely wanted CSVFILE=path/to/csv? Also, -f4 does not exist in your CSV sample, did you mean -f1? With those changes, I am getting file_A.sh, file_B.sh and file_C.sh with the quoted content, not empty files. Commented Oct 17, 2019 at 11:42
  • I agree with @Amadan : Voting to close as a typo, but glad your problem is resolved. If still trouble, try cat - >> file <<-! (note the - added after cat). Good luck to all. Commented Oct 17, 2019 at 12:36
  • thank you @Amadan, I corrected the typo in the example, but it seems it's not a good reproducible example of my problem because in my original code I am still getting the output in the console and the "bad substitution" error, so I assume it's something in my script that's not playing well with capturing the output of cat... Commented Oct 17, 2019 at 12:44
  • If your minimal reproducible example is not reproducible, there's really nothing we can do though. Commented Oct 17, 2019 at 12:46

2 Answers 2

3

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

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

Comments

0

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)

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.