2

I'm trying to get values from a MySQL database, for a later substitution with perl, everything works fine but if a record contain space " " the variables will be set uncorrectly.

Example if in the database I have:

  • sede = "street"
  • fede = "calvin and hobbes"
  • lede = "12"

the result for the variables will be:

  • $TAGSEDE = "steet"
  • $TAGFEDE = "calvin"
  • $TAGLEDE = "and"

I understood there is something wrong in setting $DBDATAF but, I can't identify it (english isn't my mother language so some misunderstanding are more than a possibility).

DBDATAF=$(mysql -u$DBUSER -p$DBPASS -se "USE $DBNAME; SELECT sede, fede, lede FROM $DBTABL WHERE cf='$CFPI'")

read TAGSEDE TAGFEDE TAGLEDE <<< $DBDATAF



/usr/bin/perl -p -i -e "s/TAGDATAINSERT/$TAGDATAINSERT/g" $i
0

1 Answer 1

2

Your code breaks down for two reasons:

  1. When $DBDATAF is passed to the <<< operator, the tabs are discarded. To keep them, double quote the variable as shown below.

  2. read separates the input line into words using the IFS special variable. By default, it separates on tab, space or newline. So even though tabs are now preseved when passed to <<<, the read command splits on spaces also. Setting IFS to a tab makes read split as desired. Putting the IFS assignment and read on one line ensures that IFS returns to the default after read exits

IFS="$( echo -e '\t' )" read TAGSEDE TAGFEDE TAGLEDE <<< "$DBDATAF"
Sign up to request clarification or add additional context in comments.

3 Comments

Explanation: The OPs code breaks down in the read call for 2 reasons: 1. When $DBDATAF is passed to the <<< operator tabs are discarded. To keep them double quote the variable as shown above. 2. read separates the input line into words using the IFS special variable which by default separates on tab, space or newline. So even though tabs are now preseved when passed to <<< the read command splits on spaces also. Setting IFS to only use tab characters gets around this. Finally, putting the IFS assignment and read on one line ensures that IFS returns to the default after read exits
Thanks, @benrifkah. Incorporated your comment into my answer.
Thanks guys, clear and smooth! using IFS reading one line is perfect. Works also with 20 variables to read.

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.