我有一个文件,每行都是逗号分隔的值列表。例如,
1, a, b, c, d, e 2, x, y, z现在我想在
bash
中进行转换,如下所示:
1 a 1 b 1 c 1 d 1 e 2 x 2 y 2 z如何使用
shell (bash)
脚本实现?awk -F, '{for(i=2;i<=NF;i++)print $1,$i}' temp
以下进行测试:
> cat temp
1, a, b, c, d, e
2, x, y, z
> awk -F, '{for(i=2;i<=NF;i++)print $1,$i}' temp
1 a
1 b
1 c
1 d
1 e
2 x
2 y
2 z
while read line
do
arrIN=(${line//,/ })
## make a loop and echo them
## arrIN[0] will have the initial number
done < $file
# $file is the input file you are reading
我明白您需要一个shell脚本,但它必须是bash吗?例如,我通常会使用更高级别的脚本语言和CSV库。例如Perl
和Text::CSV。