通过文件( csv )解析并逐行处理的 Shell 脚本 [英] Shell script to parse through a file ( csv ) and process line by line

查看:64
本文介绍了通过文件( csv )解析并逐行处理的 Shell 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨需要一个shell脚本来解析csv文件 - 逐行然后逐字段]

Hi Need a shell script to parse through the csv file - Line by line and then field by field ]

文件看起来像这样

X1,X2,X3,X4
Y1,Y2,Y3,Y4

我需要提取这些 X1、X2 中的每一个....

I need to extract each of these X1,X2....

我写了一个脚本,但如果一行超过一行,它就会失败..

I wrote a script but it fails if the line exceeds one line..

推荐答案

这是我的做法.

首先我设置 IFS 环境变量来告诉 read ," 是字段分隔符.

First i set the IFS environment variable to tell read that "," is the field separator.

export IFS=","

鉴于包含您提供的数据的文件输入",我可以使用以下代码:

Given the file "input" containing the data you provided, I can use the following code:

cat test | while read a b c d; do echo "$a:$b:$c:$d"; done

快速回顾一下上面发生的事情.cat test | 读取文件并将其通过管道传送到 while.whiledodone 之间运行代码,而 read 返回 true.read 从标准输入中读取一行,并根据 $IFS 的值将其分成变量(a"、b"、c"和d").最后 echo 只显示我们读取的变量.

To quickly recap what is going on above. cat test | reads the file and pipes it to while. while runs the code between do and done while read returns true. read reads a line from standard input and separates it into variables ("a", "b", "c" and "d") according to the value of $IFS. Finally echo just displays the variables we read.

这给了我以下输出

X1:X2:X3:X4
Y1:Y2:Y3:Y4

顺便说一句,BASH 手册总是很好的读物.每次阅读都会学到新东西.

BTW, the BASH manual is always good reading. You'll learn something new every time you read it.

这篇关于通过文件( csv )解析并逐行处理的 Shell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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