Bash Shell脚本与IFS嵌套在一起的while循环 [英] Bash shell script Nested while loop with IFS
问题描述
我正在尝试使用bash shell脚本解析一组csv文件,这些文件的外观如下:
I'm trying to parse a set of csv files using bash shell script the files looks as below:
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
我尝试使用2个while循环来解析这些文件:
I've tried parsing these files using 2 while loops:
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
并希望此代码输出
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
推荐答案
在第二个循环中,您没有按,
进行正确拆分. read
通常按IFS
,并为变量分配值,每个变量一个字段,其余的进入提供的最后一个变量.但是,如果您仅提供一个变量,那么所有内容都将存储在此处.
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. But if you provide only one variable, everything just gets stored there.
相反,让read
被,
拆分为一个数组,然后循环遍历该数组中的值,如下所示:
Instead, let read
split by ,
into an array, then loop over values in that array, like this:
#!/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
您将获得:
key1,abc
key1,cdf
key1,123
key1,456
key2,abc
key2,cdf
key2,123
key2,456
key3,abc
key3,cdf
key3,123
key3,456
这篇关于Bash Shell脚本与IFS嵌套在一起的while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!