gpt4 book ai didi

mysql - bash 脚本中的循环未捕获文件中的所有行

转载 作者:行者123 更新时间:2023-11-29 22:20:13 25 4
gpt4 key购买 nike

我当前的代码正在检查 .csv 文件,然后查询数据库以获取从角色和任务派生的信息。但是,脚本的这一部分仅读取 .csv 文件的第一行。关于如何读取 .csv 的多行有什么建议吗?

#!/bin/bash
> sql_stmnts.txt
> bad_info.txt

INPUT_FILE='test.csv'

IFS=','

while read f1 f2 f3 f4 f5 f6 f7; do

#echo "f1='$f1', f2='$f2', f3='$f3', f4='$f4', f5='$f5', f6='$f6', f7='$f7'"

user_id=$(echo "${f1//\"/}")
first_name=$(echo "${f2//\"/}")
last_name=$(echo "${f3//\"/}")
title=$(echo "${f4//\"/}")
requestor=$(echo "${f5//\"/}")
request_email=$(echo "${f6//\"/}")
roles=$(echo "$f7"| sed 's/"\(.[^"]*\)".*/\1/')
tasks=$(echo "$f7"| sed 's/".[^"]*".*"\(.[^"]*\)"/\1/')

roles=${roles//, /,}
tasks=${tasks//, /,}

for i in $roles
do
if sql_string=$(sshpass -p XXXXXX ssh jlefler@11.11.11.11 'mysql --skip-column-names -u root -pxxxxxx database -e "select id from roles where binary role_name='"'${i}';"'"'); then
if [[ -n $sql_string ]]; then
echo "insert into user_roles (USER_ID, ROLE_ID, version) select id, $sql_string, 1 from users where user_id in ('$user_id');" >> sql_stmnts.txt
else
echo "$user_id - $i is a bad role" >> bad_info.txt
fi
else
echo "Query Didn't Execute"
fi
done

for i in $tasks
do
if sql_string=$(sshpass -p XXXXXXX ssh jlefler@11.11.11.11 'mysql --skip-column-names -u root -xxxxxxx database -e "select id from groups where binary group_name='"'${i}';"'"'); then
if [[ -n $sql_string ]]; then
echo "insert into membership (USER_ID, group_ID, version) select id, $sql_string, 1 from users where user_id in ('$user_id');" >> sql_stmnts.txt
else
echo "$user_id - $i is a bad task" >> bad_info.txt
fi
else
echo "Query Didn't Execute"
fi
done

done < $INPUT_FILE

使用 bash -x 选项运行时,第一行末尾输出:

+ sql_string=3
+ [[ -n 3 ]]
+ echo 'insert into membership (USER_ID, group_ID, version) select id, 3, 1 from users where user_id in ('\''jlefler'\'');'
+ read f1 f2 f3 f4 f5 f6 f7

最佳答案

您可以使用for循环。我只是将 sql_string 设置为随机#。该示例只是说明您可以使用 for 循环来实现相同的目的。

例如:[c1@服务器 CLI]$ cat 1.sh

#!/bin/bash

# Create fresh .txt files. You don't have to use the next 2 lines if you want them to be appended each time you run your script.
>a.txt
>b.txt

arr=("Case Manager" "Case Collector" "Engineer")
for line in "${arr[@]}"; do
##I'm just setting sql_string to a value. Set accordingly per your use.
if sql_string=$RANDOM ; then
if [[ -n $sql_string ]]; then
echo $line - "$sql_string" >> a.txt
else
echo "No Data Found" >> b.txt
fi
else
echo "Query Didn't Execute"
fi
done

[c1@server CLI]$ cat a.txt

Case Manager - 13101
Case Collector - 3325
Engineer - 30248

[c1@服务器 CLI]$

关于mysql - bash 脚本中的循环未捕获文件中的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30805662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com