迭代 csv 上的行以将列保存为变量

迭代 csv 上的行以将列保存为变量

我有一个 csv 组成如下:

Column1,Column2,Column3
A Existing text in Column1, A Date in Column2, A Integer in Column3
B Existing text in Column1, B Date in Column2, B Integer in Column3
C Existing text in Column1, C Date in Column2, C Integer in Column3

我试图在迭代文件时将每一行保存为带有 for 循环的变量:

for i in `cat file.csv`
    do
        VARIABLE=$(echo $i && echo ", Another text")
    done

而不是将变量另存为(例如,通过第一次迭代的 VARIABLE): A Existing text in Column1, A Date in Column2, A Integer in Column3, Another text

它保存为:

Column1,Column2,Column3
 , Another Text
A
 , Another Text
Existing
 , Another Text
text
 , Another Text
in
 , Another Text
Column1,
 , Another Text
A
 , Another Text
Date
 , Another Text
in
 , Another Text
Column2,
 , Another Text
A
 , Another Text
Integer
 , Another Text
in
 , Another Text
Column3
 , Another Text
B
 , Another Text
Existing
 , Another Text
text
 , Another Text
...(continues)

for循环制动每项工作而不是仅仅将整条生产线视为一个整体是否有特定的原因?

答案1

问题是设置$IFS

echo -n "$IFS" | od -t c -t x1
0000000      \t  \n
         20  09  0a

的输出cat在每个空格、制表符或换行符处进行分割。您希望它仅在换行符处拆分。所以这会起作用:

IFS='
'
for i in `cat file.csv`
    do
        VARIABLE=$(echo $i && echo ", Another text")
    done

但这不是一个好方法。你应该读行。而且您也不应该使用命令替换和echo组合变量。

while IFS= read -r line; do
    VARIABLE="${line}, Another text"
done <file.csv

答案2

如果您只想有效地向 CSV 添加另一列,请尝试使用 CSV 工作的工具。

GoCSV添加命令可以轻松做到这一点:

gocsv add -n 'Column4' -t ' Another text' sample.csv

给我:

Column1,Column2,Column3,Column4
A Existing text in Column1," A Date in Column2"," A Integer in Column3"," Another text"
B Existing text in Column1," B Date in Column2"," B Integer in Column3"," Another text"
C Existing text in Column1," C Date in Column2"," C Integer in Column3"," Another text"

如果您不想将其视为实际的 CSV 文件(由于前导空格,因此需要所有双引号),您可以尝试以下操作:

sed 's/.$/, Another text/' sample.csv
Column1,Column2,Column3, Another text
A Existing text in Column1, A Date in Column2, A Integer in Column3, Another text
B Existing text in Column1, B Date in Column2, B Integer in Column3, Another text
C Existing text in Column1, C Date in Column2, C Integer in Column3, Another text

但!,仅当您的文件有尾随/终端换行符时才有效。否则,这将破坏最后一个字符(在最后一列,最后一行)。

相关内容