使用SQL获取的拆分管道分隔的字符串

时间:2019-05-01 04:33:28

标签: linux string shell

我的shell脚本执行SQL来以以下格式获取数据:

JOB_ID_001|[PROD] This is a mail subject one ${application_date}|a@example.com,b@example.com
JOB_ID_002|[PROD] This is a mail subject two ${application_date}|c@example.com,b@example.com

我想分割这个用管道分隔的字符串,但是输出看起来很奇怪,如下所示:

JOB_ID_001[0]
JOB_ID_001[1]
JOB_ID_001[2]
This[0]
This[1]
This[2]
is[0]
is[1]
is[2]
a[0]
a[1]
a[2]
mail[0]
mail[1]
mail[2]
subject[0]
subject[1]
subject[2]
one[0]
one[1]
one[2]
${application_date}[0]
${application_date}[1]
${application_date}[2]
example.com,b@example.com[0]
example.com,b@example.com[1]
example.com,b@example.com[2]
JOB_ID_002[0]
JOB_ID_002[1]
JOB_ID_002[2]
This[0]
This[1]
This[2]
is[0]
is[1]
is[2]
a[0]
a[1]
a[2]
mail[0]
mail[1]
mail[2]
subject[0]
subject[1]
subject[2]
two[0]
two[1]
two[2]
${application_date}[0]
${application_date}[1]
${application_date}[2]
ple.com,b@example.com[0]
ple.com,b@example.com[1]
ple.com,b@example.com[2]

我想要的输出是:

JOB_ID_001
[PROD] This is a mail subject one ${application_date}
a@example.com,b@example.com
JOB_ID_002
[PROD] This is a mail subject two ${application_date}
c@example.com,b@example.com

以便我可以继续使用这些字符串。

我的shell脚本如下:

email_configs=(`sqlplus -silent $DB_CONN <<-EOF
    whenever sqlerror exit 1 oserror exit oscode
    set heading off feedback off echo off verify off pagesize 0
    $sql_subject_of_mail;
    exit;
    EOF`)

for i in "${!email_configs[@]}"
do
    email_config=${email_configs[i]}

    IFS='|' read -r -a email_config_array <<< "$email_config"

    job_id=$email_config_array[0]
    subject_of_mail=$email_config_array[1]
    to_mail_id=$email_config_array[2]

    echo $job_id
    echo $subject_of_mail
    echo $to_mail_id

done

我从this页检查了一些替代解决方案,但是在输出$ {application_date}部分中缺少该内容或存在其他问题。

有人能对我的错误有个想法吗?

1 个答案:

答案 0 :(得分:0)

未正确设置$email_configs数组。它使用空格作为数组定界符,而不是换行符。

而不是设置数组,而是循环读取sqlplus的输出。

while IFS='|' read -r job_id subject_of_mail to_mail_id
do
    echo "$job_id"
    echo "$subject_of_mail"
    echo "$to_mail_id"
done < <(sqlplus -silent $DB_CONN <<-EOF
    whenever sqlerror exit 1 oserror exit oscode
    set heading off feedback off echo off verify off pagesize 0
    $sql_subject_of_mail;
    exit;
    EOF 
)