【问题标题】:Write to file from within a for loop in Bash从 Bash 的 for 循环中写入文件
【发布时间】:2020-02-14 07:44:52
【问题描述】:

假设我有以下 csv 文件:

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

对于文件第一列中的每个唯一值i,我想编写一个使用该值进行一些处理的脚本。我打算这样做:

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

但是,这会为它循环的所有 i 值创建空文件,并将文件的实际内容打印到控制台。

有没有办法将输出重定向到文件?

【问题讨论】:

  • 您对这些价值观的目标想法是什么?发布最终结果应该是什么
  • $CSVFILE=path/to/csv 是一个错误。你可能想要CSVFILE=path/to/csv?此外,您的 CSV 样本中不存在 -f4,您的意思是 -f1 吗?通过这些更改,我得到了 file_A.shfile_B.shfile_C.sh 引用的内容,而不是空文件。
  • 我同意@Amadan:投票结束是一个错字,但很高兴您的问题得到解决。如果还是有问题,试试cat - &gt;&gt; file &lt;&lt;-!(注意cat后面加的-)。祝大家好运。
  • 谢谢@Amadan,我更正了示例中的错字,但它似乎不是我的问题的一个很好的可重现示例,因为在我的原始代码中,我仍然在控制台中获得输出并且“错误替换”错误,所以我认为这是我的脚本中的某些内容无法很好地捕获 cat 的输出...
  • 如果您的minimal reproducible example 无法重现,那么我们确实无能为力。

标签: bash for-loop cat


【解决方案1】:

简单

#!/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

截图

【讨论】:

    【解决方案2】:

    试试这个:

    #!/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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-27
      • 1970-01-01
      • 1970-01-01
      • 2013-03-21
      • 2011-10-25
      • 2021-07-06
      • 2018-01-12
      • 1970-01-01
      相关资源
      最近更新 更多