Re: 4th row in txt
| From: | Paul Chvostek | Date: | Mon, 21 Apr 2003 16:32:47 +0000 |
| Subject: | Re: 4th row in txt | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-144664@lists.php.net to get a copy of this message | ||
On Mon, Apr 21, 2003 at 05:12:53PM +0200, Simon wrote:
> I have some txt files, that I would like to import to mysql. Format is:
>
> name
> last name
> city
> year
>
> How can PHP "select" only 4th row, and then put it into mysql.
For a quick-and-dirty solution, I would do this with awk wrapped in a
small shell script:
#!/bin/sh
cd /path/to/files/
ls | while read filename ; do
awk '
NR == 1 { name=$0; }
NR == 2 { lname=$0; }
NR == 3 { city=$0; }
NR == 4 { year=$0; }
END {
printf("INSERT INTO table (name,lname,city,year) VALUES
(\"%s\",\"%s\",\"%s\",\"%s\");\n", name, lname, city,
year);
}
' $filename | mysql -uDBUSER -pDBPASS DBNAME
done
Of course, this is ugly, and if you're doing it for millions of these
files every day, you'd want something that didn't launch awk once for
every file. It would be possible to do the whole thing in shell or awk.
Or php or perl or python or C or even Logo if you were off your lithium.
In PHP, the script might be more like:
#!/usr/local/bin/php -q
<?php
$fmt="INSERT INTO table (name,lname,city,year) VALUES
('%s','%s','%s','%s')";
mysql_pconnect(yadda);
mysql_select_db(yadda);
$dir="/path/to/files/";
$dh=opendir($dir);
while($file=readdir($dh)) {
if ($body=file($dir . $file)) {
printf("Inserting: %-40s\r", $file);
mysql_query(sprintf($fmt, $file[0], $file[1], $file[2], $file[3]));
}
}
?>
--
Paul Chvostek <paul@it.ca>
Operations / Abuse / Whatever
it.canada, hosting and development http://www.it.ca/