Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate MySQL table from Text file

This should be an easy one. I need to populate a table from a text file. Basically, I'd like to do this in a linux shell script. Thanks!!

Example:

  • MySQL Table

Item color shape size

  • Textfile

car blue round small

carrot red square big

apple green round medium

like image 857
Lexicon Avatar asked Dec 01 '25 16:12

Lexicon


1 Answers

You could run a query like this:

LOAD DATA INFILE 'data.txt' INTO TABLE yourTable
 FIELDS TERMINATED BY ' '
 LINES TERMINATED BY '\n'

And then all you need is to write a tiny shell script, executing the query.

Edit:

A complete script could look something like this:

#!/bin/bash
mysql databaseName<<EOFMYSQL
 LOAD DATA INFILE 'data.txt' INTO TABLE yourTable
  FIELDS TERMINATED BY ' '
  LINES TERMINATED BY '\n';
EOFMYSQL

The script could be executed like this:

chmod +x script.sh
./script.sh

You probably run into user issues, since the shell does not handle mysql directly. Try looking into how you can execute mysql without logging in. This should be part of just about any mysql backup script :-)

like image 151
Ragnar123 Avatar answered Dec 04 '25 04:12

Ragnar123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!