Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a Properties File using Shell Script and Results from a SQL Query

I am trying to create a properties file like this...

firstname=Jon
lastname=Snow
occupation=Nights_Watch
family=Stark

...from a query like this...

SELECT 
  a.fname as firstname, 
  a.lname as lastname, 
  b.occ as occupation... 
FROM 
  names a, 
  occupation b, 
  family c... 
WHERE... 

How can I do this? As I am aware of only using spool to a CSV file which won't work here?

These property files will be picked up by shell scripts to run automated tasks. I am using Oracle DB

like image 712
Debajyoti Das Avatar asked Jun 26 '13 09:06

Debajyoti Das


People also ask

How do I run a SQL query in a shell script?

To run a SQL script using SQL*Plus, place the SQL along with any SQL*Plus commands in a file and save it on your operating system. For example, save the following script in a file called "C:\emp. sql". CONNECT scott/tiger SPOOL C:\emp.


Video Answer


2 Answers

Perhaps something like this?

psql -c 'select id, name from test where id = 1' -x -t -A -F = dbname -U dbuser

Output would be like:

id=1
name=test1

(For the full list of options: man psql.)

like image 129
Denis de Bernardy Avatar answered Oct 11 '22 06:10

Denis de Bernardy


Since you mentionned spool I will assume you are running on Oracle. This should produce a result in the desired format, that you can spool straight away.

SELECT
    'firstname=' || firstname || CHR(10) ||
    'lastname=' || lastname || CHR(10) -- and so on for all fields
FROM your_tables;

The same approach should be possible with all database engines, if you know the correct incantation for a litteral new line and the syntax for string concatenation.

like image 42
RandomSeed Avatar answered Oct 11 '22 06:10

RandomSeed