[thelist] Re: bash, read from several files

Eduardo Bacchi Kienetz eduardobk at via-rs.net
Sat Apr 17 17:26:23 CDT 2004


Hi Magnus,

Try this (read the whole message first):

#!/bin/sh
export IFS="/"
for NAME in "cat name.txt emails.txt etc.txt bla.sql"
do
    psql -d nobody nobody -c "INSERT INTO contact(name) VALUES('$NAME');"
done
export IFS=" "

NAME will have every name while looping. You should note that if the 
name contains space you'd have trouble because it would save "Eduardo 
Kienetz" on two records, "Eduardo" and another record for "Kienetz". 
That's why I change the FS variable, which stands for the separator 
(which previously was SPACE).

A simpler way of accomplishing that would be this command:
cat name.txt emails.txt etc.txt bla.sql | xargs -n1 -i pgsql -d nobody 
-c "INSERT INTO contact(name) VALUES('{}')"

xargs does the magic. It will run pgsql for each line of your files 
(name.txt emails.txt etc.txt bla.sql, etc).
Each line value is represented by the {}

Regards,

Eduardo Bacchi Kienetz
Senior Support Analyst on *nix Systems

--------------------------

>Date: Sat, 17 Apr 2004 03:57:13 +0200 (CEST)
>From: "=?iso-8859-1?Q?Magnus_=D8stergaard?=" <magnus at slackware.adsl.dk>
>To: <thelist at lists.evolt.org>
>Subject: [thelist] bash, read from several file
>Message-ID: <17441.212.242.116.232.1082167033.squirrel at webmail.firstimpact.dk>
>Content-Type: text/plain; charset=iso-8859-1
>MIME-Version: 1.0
>Content-Transfer-Encoding: 8bit
>Precedence: list
>Reply-To: "thelist at lists.evolt.org" <thelist at lists.evolt.org>
>Message: 6
>
>Hi,
>
>I am trying to populate a postgresql db with values from several files.
>In each file, each line correspont to the same line number in the other
>files.
>The problem is how do I make my loop?
>
>This is what I've got so far:
>
>#!/bin/sh
>while read name;
> do psql -d nobody nobody -c "INSERT INTO contact(name) VALUES('$name');" ;
>done< ./name.txt
>
>But this only reads one file.
>
>How can I read from two files (or more) at one time. Say name.txt and
>email.txt and then do.
>
>"INSERT INTO contact(name,email) VALUES('$name','$email');"
>
>I am looking for a bash solution, but a php one could help me.
>
>// Magnus
>  
>


More information about the thelist mailing list