0

I just started programming in shell script and I have a file that looks like this:

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

My main goal in this is to migrate all those students into a mysql database, my code would be something like this:

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

I know that to do this I need to use sed or something like it, but I just can't figure it out how. Thanks in advance.

4

1 回答 1

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 教程

IHTH

于 2013-04-20T02:34:09.057 回答