0

I have a sqlite with a table with 2 columns. I would like to get the two values of the columns in every variable or in an array. For instance:

table A
COLUMN A         COLUMN B
credit and risk  David
nothing          susan
.....

and I would like to obtain: Variable A="credit and risk" and variable B="David" then Variable A ="nothing" and variable B= "susan" and so on. I'm trying with these code but if the column A have space I can't get the string complete, for example I obtain "credit" only. My code:

valores=($(sqlite3 alcampo.db "select DESCRIPTION, URL  FROM SUBCATEGORYS"))

cnt=${#valores[@]}
echo "cuenta es ... $cnt"
for (( i=0 ; i<cnt ; i++ ))
do
    echo "Record No. $i: ${valores[$i]}"
    fieldA=${valores[0]}
echo "campo a es ... $fieldA"
    fieldB=${valores[1]}
echo "campo B es ... $fieldB"

done

Could you help me please? Thanks

1
  • See Bash FAQ 001 for help on how to read lines from streams. Then you just need to pick a delimiter that isn't in your data to split on. Commented May 12, 2016 at 17:02

1 Answer 1

1

There might be better ways to get this done.
It sounds like you don't want to keep the variables after you echo them.

while read line; do

  fieldA=$( echo "$line" | sed -n "s/\(.*\)\s\{2,\}.*/\1/p" )
  fieldB=$( echo "$line" | sed -n "s/.*\s\{2,\}\(.*\)/\1/p" )

  echo "campo A es ... ${fieldA}"
  echo "campo B es ... ${fieldB}"

done < <(sqlite3 alcampo.db "select DESCRIPTION, URL FROM SUBCATEGORYS") 

This will ready your command "sqlite3 ..." directly into the while loop. The while loop will assign each line to the variable "$line".

We then echo the $line variable and sed it to grab the information we want. The sed is based on having 2 or more spaces between the columns...it was the only way I could think to delimit the data based off of what you posted.

  • $( ) -- command substitution
  • -n -- don't print
  • s -- substitute
  • \( -- begin capture group 1
  • .* -- match anything
  • \) -- end capture group 1
  • \s{2,} -- 2 or more white-space characters
  • .* -- anything else
  • \1 -- output capture group 1
  • p -- print it

I hope this helps. Let me know.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.