通过文件( 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
.while
在 do
和 done
之间运行代码,而 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.