循环遍历 CSV 文件并在读取时创建新的 csv 文件? [英] Loop through CSV file and create new csv file with while read?

查看:32
本文介绍了循环遍历 CSV 文件并在读取时创建新的 csv 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

while read $field1 $field2 $field3 $field4
do
  $trimmed=$field2 | sed 's/ *$//g'
  echo "$trimmed","$field3" >> new.csv
done < "$FEEDS"/"$DLFILE"

现在的问题是 read 我不能让它拆分字段 csv 样式,可以吗?请参阅下面的输入 csv 格式.

Now the problem is with read I can't make it split fields csv style, can I? See the input csv format below.

我需要取出第 3 列和第 4 列,去掉第 2 列的填充,而且我不需要引号.

I need to get columns 3 and 4 out, stripping the padding from col 2, and I don't need the quotes.

带有列号的 CSV 格式:12 24(")25(,)26(")/27(Field2values) 42(")/43(,)/44(Field3 十进制值)"Field1_constant_value","Field2values ",Field3,Field4

Csv format with col numbers: 12 24(")25(,)26(")/27(Field2values) 42(")/43(,)/44(Field3 decimal values) "Field1_constant_value","Field2values ",Field3,Field4

Field1 是常数且无关紧要.数据被引用,从引号内的 2-23 开始.Field2 用引号内的 cols 27-41 固定,数据在左边,右边用空格填充.Field3 是一个十进制数,小数点前有 1,2 或 3 位数字,小数点后有 2 位,没有填充.从第 74 栏开始.Field4 是一个日期,我现在不太关心它.

Field1 is constant and irrelevant. Data is quoted, goes from 2-23 inside the quotes. Field2 fixed with from cols 27-41 inside quotes, with the data at the left and padded by spaces on the right. Field3 is a decimal number with 1,2, or 3 digits before the decimal and 2 after, no padding. Starts at col 74. Field4 is a date and I don't much care about it right now.

推荐答案

是的,可以使用 read;您所要做的就是重置环境变量 IFS -- 内部字段分隔符 --,这样它就不会按当前值(默认为空白)拆分行,而是按您自己的分隔符.

Yes, you can use read; all you've got to do is reset the environment variable IFS -- Internal Field Separator --, so that it won't split lines by its current value (default to whitespace), but by your own delimiter.

考虑具有给定内容的输入文件a.csv":

Considering an input file "a.csv", with the given contents:

1,2,3,4

2,3,4,5

6,3,2,1

你可以这样做:

IFS=','
while read f1 f2 f3 f4; do
    echo "fields[$f1 $f2 $f3 $f4]"
done < a.csv

输出为:

字段[1 2 3 4]

fields[1 2 3 4]

字段[2 3 4 5]

fields[2 3 4 5]

字段[6 3 2 1]

fields[6 3 2 1]

这篇关于循环遍历 CSV 文件并在读取时创建新的 csv 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆