Shell脚本从文件中提取数据

时间:2013-04-19 20:26:05

标签: mysql shell sed extract

我刚开始用shell脚本编程,我有一个看起来像这样的文件:

stuff that doesn't matter
doesn't matter
matter

*LINE 35*School: xxxxx -> NAME: xxxxx AGE: xxx DESCRIPTION: xxxxxxxxxx
School: yyyyy -> NAME: yyyyy AGE: yyy DESCRIPTION: yyyyyyyyyy
School: zzzzz -> NAME: zzzzz AGE: zzz DESCRIPTION: zzzzzzzzzz
School: aaaaa -> NAME: aaaaa AGE: aaa DESCRIPTION: aaaaaaaaaa
6 lines of stuff after the important information

我的主要目标是将所有学生迁移到mysql数据库,我的代码将是这样的:

nstudents=(( $(wc -l file | cut -d ' ' -f1) - 41) #41 comes from 35+6
i=1
while [ $i != $nstudents ]
do
$school=[I don't know how to extract school number $i]
$name=[I don't know how to extract name number $i]
$age=[I don't know how to extract age number $i]
$desc=[I don't know how to extract description number $i]
mysql #upload
$i= (( $i + 1 ))
done

我知道要做到这一点,我需要使用sed或类似的东西,但我无法弄清楚如何。提前谢谢。

1 个答案:

答案 0 :(得分:1)

根据对数据真实情况的最佳猜测,为您的问题指出一个shell-ish解决方案,试试这个

cat inputFile
stuff that doesn't matter
doesn't matter
matter

*LINE 35*School: xxxxx -> NAME: xxxxx AGE: xxx DESCRIPTION: xxxxxxxxxx
School: yyyyy -> NAME: yyyyy AGE: yyy DESCRIPTION: yyyyyyyyyy
School: zzzzz -> NAME: zzzzz AGE: zzz DESCRIPTION: zzzzzzzzzz
School: aaaaa -> NAME: aaaaa AGE: aaa DESCRIPTION: aaaaaaaaaa
6 lines of stuff after the important information

awk -F: '/School/{
    gsub(/ -> /, ""); sub(/School/,""); sub(/NAME/,"")
    sub(/AGE/,""); sub(/DESCRIPTION/,"")
    printf("insert into MyTable values (\"%s\", \"%s\", \"%s\", \"%s\")\n",  $2, $3, $4, $5)     
}' inputFile

<强>输出

insert into MyTable values (" xxxxx", " xxxxx ", " xxx ", " xxxxxxxxxx")
insert into MyTable values (" yyyyy", " yyyyy ", " yyy ", " yyyyyyyyyy")
insert into MyTable values (" zzzzz", " zzzzz ", " zzz ", " zzzzzzzzzz")
insert into MyTable values (" aaaaa", " aaaaa ", " aaa ", " aaaaaaaaaa")

如果您喜欢,请查看grymoire awk tutorial

IHTH