我正在尝试使用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
我尝试使用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
并期望此代码输出
key1,abc
key1,cdf
key1,123
key1,456 and so on...
但是,当我运行此代码表明第二个循环没有被执行时,我没有得到任何输出。任何正确方向的指针都会有所帮助。感谢
答案 0 :(得分:2)
在第二个循环中,,
没有正确分割。 read
通常按IFS
拆分,并将值分配给变量,每个变量一个字段,剩余部分进入提供的最后一个变量。但是如果你只提供一个变量,那么一切都会存储在那里。
相反,让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
你会得到:
key1,abc
key1,cdf
key1,123
key1,456
key2,abc
key2,cdf
key2,123
key2,456
key3,abc
key3,cdf
key3,123
key3,456