[英]Write to file from within a for loop in Bash
Let's say I have the following csv file:假设我有以下 csv 文件:
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
,我想编写一个使用该值进行一些处理的脚本。 I go about doing it this way:我 go 关于这样做:
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.但是,这会为它循环的所有
i
值创建空文件,并将文件的实际内容打印到控制台。
Is there a way to redirect the output to the files instead?有没有办法将 output 重定向到文件?
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.