Bash:变量在“for”中未完整读取,因为行包含空格

Bash:变量在“for”中未完整读取,因为行包含空格

for命令中,由于空格,变量未完全保存。

源文件in.csv

VPricingCurrency,Currency,Transactions,VPricingCurrency,Deal,VPricingCurrency
CustomerPriceGroup,Customer Price Group,AccountDS,AccountType,AccountDS,AccountType

命令:

for i in $(cat in.csv);
do
  echo "$i"
done

输出:

VPricingCurrency,Currency,Transactions,VPricingCurrency,Deal,VPricingCurrency
CustomerPriceGroup,Customer
Price
Group,AccountDS,AccountType,AccountDS,AccountType

如何使第二行充满空格。

谢谢。

答案1

为了避免 shell 进行单词拆分,请使用循环while而不是for循环:

while IFS= read -r i; do 
  echo "$i"
done < in.csv
VPricingCurrency,Currency,Transactions,VPricingCurrency,Deal,VPricingCurrency
CustomerPriceGroup,Customer Price Group,AccountDS,AccountType,AccountDS,AccountType

也可以看看:

答案2

使 IFS 以结束线为界。

IFS=$'\n'
for i in $(cat in.csv);
do
  echo "$i"
done

根据输入文件得到两行

VPricingCurrency、货币、交易、VPricingCurrency、交易、VPricingCurrency CustomerPriceGroup、客户价格组、AccountDS、AccountType、AccountDS、AccountType

相关内容