0

I am trying to extract one query at a time from an SQL file.

This is what I have tried

index1=1
index2=1
while read -n1 char; do
if [[ $char == ";" ]]
  then
     SUBSTRING=$(awk 'substr($index1,$index2)' sql1Temp.sql)
     echo $SUBSTRING 
    index1=$index2
fi 
((index2+=1))

done <sql1Temp.sql

My SQL file look like this:

sqlFile.sql

select *from test1;

select *from test2;

select *from test3;

I am getting this as a result:

wedtorque@wedtorque-VirtualBox:~/Desktop$ ./masterFile.sh
select *from test1; select *from test2; select *from test3;
select *from test1; select *from test2; select *from test3;
select *from test1; select *from test2; select *from test3;
wedtorque@wedtorque-VirtualBox:~/Desktop$

Whereas I was expecting something like this:

wedtorque@wedtorque-VirtualBox:~/Desktop$ ./masterFile.sh
select *from test1;
select *from test1;
select *from test1;
wedtorque@wedtorque-VirtualBox:~/Desktop$

Also when I echo the $char inside while loop, it prints the file names every time $char gets the * from queries, select *from test1; etc

Something like this

wedtorque@wedtorque-VirtualBox:~/Desktop$ ./masterFile.sh
s
e
l
e
c
t

masterFile.sh sql1result.sql sql1.sql sql1Temp.sql sql2.sql Untitled Document
f
r
o
m

t
e
s
t
1
select *from test1; select *from test2; select *from test3;
;
0

Not 100% sure what you are doing, but I'll take a guess.

The .sql file, in my test case I'll call it test.sql:

select * from test1;
select * from test2;
select * from test3;

And the script to read and echo that sql data:

#!/bin/sh

# Get the raw sql data
RAW=`cat test.sql`

# We want to split the raw sql on a line return.
IFS="
"

# Echo out each line? Not sure if this is what you want.
for sql in $RAW
do
    echo "SQL line: [${sql}]"
done

exit

This will give you the following result:

SQL line: [select * from test1;]
SQL line: [select * from test2;]
SQL line: [select * from test3;]

I think the bit you are missing is the IFS part. From man sh:

IFS  Input Field Separators. This is normally set to ⟨space⟩, 
     ⟨tab⟩, and ⟨newline⟩.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.