【问题标题】:Separate string read from CSV into array is not working从 CSV 读取到数组的单独字符串不起作用
【发布时间】:2020-11-06 06:45:43
【问题描述】:

所以我的 CSV 文件看起来像这样:

repo_name1,path1,branch1 branch2

我用以下代码阅读它:

INPUT=repos.csv
OLDIFS=$IFS
IFS=','

[ ! -f $INPUT ] && { echo "$INPUT file not found"; exit 99; }
while read repo_name local_path branches
do
    printf "\n"
    echo "Repository name: $repo_name"
    echo "Local path: $local_path"
    cd $local_path
    for branch in $branches
    do
        echo branch
        printf "\n"
    done
done < $INPUT
IFS=$OLDIFS

我想在 bash 脚本中将 branch1 和 branch2 拆分为一个数组。

我尝试了我在 stackoverflow 上找到的所有内容 Loop through an array of strings in Bash?, Split string into an array in Bash, Reading a delimited string into an array in Bash ,但没有任何工作正常,我得到的是包含 1 个元素的数组 -> branch1 branch2

任何想法我做错了什么?

【问题讨论】:

  • 您已设置IFS=',' 并尝试读取以空格分隔的数组
  • 尝试IFS=",$IFS" 添加逗号,但保留通常的分隔符。 (而echo branch 应该是echo "$branch"。)
  • for branch in $branches -- 您使用 IFS= 来拆分 $branches,$branches 中没有逗号,因此您只能通过该循环进行一次迭代。

标签: bash csv


【解决方案1】:

您必须分两步完成:

input=repos.csv

while IFS=, read -r repo path branchstr; do
    read -ra branches <<< "$branchstr"
    declare -p repo path branches
done < "$input"

导致

$ ./split
declare -- repo="repo_name1"
declare -- path="path1"
declare -a branches=([0]="branch1" [1]="branch2")

【讨论】:

  • 谢谢,这对我有用。你能告诉我如何摆脱这个“声明”输出吗?
  • @cropyeee 这是declare 命令的输出——查看变量包含什么的简单方法。只需将declare 行替换为您想要对repopathbranches 执行的任何操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-27
  • 2016-03-22
  • 2023-03-12
  • 1970-01-01
相关资源
最近更新 更多