我有一个sqlite数据库表,其中有三列存储Name,Location和Notes。似乎所有内容都已正确存储,因为使用sqlite命令行时,我会看到正确的列数,并且数据已正确分组。
使用bash脚本(这是一项要求)访问数据时出现问题。 “Notes”列存储可能是多行的数据(使用换行符等)。当我查询此表时,使用以下内容:
stmt="Select name, location, notes from t1"
sqlite3 db "$stmt" | while read ROW;
do
name=`echo $V_ROW | awk '{split($0,a,"|"); print a[1]}'`
location=`echo $V_ROW | awk '{split($0,a,"|"); print a[2]}'`
notes=`echo $V_ROW | awk '{split($0,a,"|"); print a[3]}'`
done
我最终得到了一切正常,直到notes列中的第一个换行符。在此之后,每个注释行被视为一个新行。在bash中处理这个问题的正确方法是什么?
答案 0 :(得分:0)
由于数据是管道分离的,你可以这样做(未经测试):将每一行读入一个数组;检查数组的大小
sqlite3 db "$stmt" | {
full_row=()
while IFS='|' read -ra row; do
if [[ ${#row[@]} -eq 3 ]]; then
# this line contains all 3 fields
if [[ ${#full_row[@]} -eq 0 ]]; then
: # "row" is the first row to be seen, nothing to do here
else
name=${full_row[0]}
location=${full_row[1]}
notes=${full_row[2]}
do_something_with "$name" "$location" "$notes"
#
# not necessary to use separate vars
# do_something_with "${row[@]}"
fi
# then store the current row with incomplete notes
full_row=( "${row[@]}" )
else
# only have notes.
full_row[2]+=" "${row[0]}
fi
done
}
您最好采取措施确保备注字段不包含您的字段分隔符(|
)