简体   繁体   English

Bash Shell脚本与IFS嵌套在一起的while循环

[英]Bash shell script Nested while loop with IFS

I'm trying to parse a set of csv files using bash shell script the files looks as below: 我正在尝试使用bash shell脚本解析一组csv文件,这些文件如下所示:

File1: /tmp/test.txt
key1,key1file.txt
key2,key2file.txt
key3,key3file.txt

Files: /tmp/inter/key1file.txt
abc,cdf,123,456

Files: /tmp/inter/key2file.txt
abc,cdf,123,456

Files: /tmp/inter/key3file.txt
abc,cdf,123,456

I've tried parsing these files using 2 while loops: 我试过使用2 while循环解析这些文件:

while IFS="," read keycol keyfile
do
    while IFS="," read keyval
     do
     echo "inside inner while loop"
     echo "$keycol|$keyval"
    done < "/tmp/inter/$keyfile"
done < /tmp/test.txt

and expecting this code to output 并期望输出此代码

key1,abc
key1,cdf
key1,123
key1,456 and so on...

However, i'm not getting any output when i run this code which indicates the second loop is not being executed. 但是,运行此代码表示未执行第二个循环时,我没有得到任何输出。 Any pointers in the right direction would be of help. 正确方向的任何指点都会有所帮助。 Thanks 谢谢

You are not properly splitting by , in your second loop. 在第二个循环中,您没有被正确分割。 read generally splits by IFS , and assigns values to variables, one field per variable, and the remaining goes into the last variable provided. read通常由IFS拆分,并为变量分配值,每个变量一个字段,其余的进入提供的最后一个变量。 But if you provide only one variable, everything just gets stored there. 但是,如果仅提供一个变量,则所有内容都将存储在此处。

Instead, let read split by , into an array, then loop over values in that array, like this: 相反,让read通过分割,该阵列中到一个数组,然后遍历值,如下所示:

#!/bin/bash
while IFS="," read keycol keyfile; do
    while IFS="," read -a values; do
        for val in "${values[@]}"; do
            echo "$keycol,$val"
        done
    done < "/tmp/inter/$keyfile"
done < /tmp/test.txt

You'll get: 你会得到:

key1,abc
key1,cdf
key1,123
key1,456
key2,abc
key2,cdf
key2,123
key2,456
key3,abc
key3,cdf
key3,123
key3,456

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM