mysql - 已解决 - 如何用 sed 替换行首和行尾以及 concat 行
问题描述
我想将我的 SQL 查询的结果存储在一个变量中,以便在“in”子句的另一个查询中使用它。
当我使用 INT 列表执行此操作时,我找到了解决方案,但在 varach 的上下文中我还没有找到它。
你有想法吗?
有关信息,对于我使用的 int:
listID=$(/usr/mysql-5.5.40/bin/mysql -u$USER -p$PASSWORD -h$HOST -P$PORT $SCHEMA -e "SELECT ID FROM MYTABLE where NAME="toto";"|sed '1d;:a;N;$!ba;s/\n/,/g' )
在这种情况下,我可以使用 listID
NBMESSAGE=$(/usr/mysql-5.5.40/bin/mysql -u$USER -p$PASSWORD -h$HOST -P$PORT $SCHEMAMESSAGE -e "SELECT count(*) FROM MESSAGE where AUTOR_ID in ($listID)"|sed '1d')
然后,我做
echo " Nombre de message $NBMESSAGE "
谢谢编辑:我已经测试了我的请求,结果很好并产生了这个,在数据库 ID 中是 VARCHAR:
ID
1
12
13
14
15
16
17
当我通过 |sed '1d;:a;N;$!ba;s/\n/,/g' 我得到
1,12,13,14,15,16,17
但我想要:
'1','12','13','14','15','16','17'
当我设法得到这个结果时,我会将它传递给另一个进行计数的查询。我也会发布它。
编辑2:
我用这个命令解决了我的问题,我与你分享:
listID=$(/usr/mysql-5.5.40/bin/mysql -u$USER -p$PASSWORD -h$HOST -P$PORT $SCHEMA -e "SELECT ID FROM MYTABLE where NAME="toto";"|se
d '1d;:a;N;$!ba;s/\n/'"'"','"'"'/g;s/^/'"'"'/g;s/$/'"'"'/g')
在这种情况下,当我做一个
echo " $listID "
我得到'1','2','3','4'
谢谢
解决方案
由于我没有包含您的数据集的 MySQL 数据库,因此我构建了这个简单的脚本来打印您期望的输出:
打印输出.bash
#!/bin/bash
#
echo "ID"
echo "1"
echo "12"
echo "13"
echo "14"
echo "15"
echo "16"
echo "17"
第二个脚本处理上述脚本的输出:
#!/bin/bash
# Read the result of the command into an array
# If the command fails, \0 is returned. The RESULTS array will have only 1 empty element
IFS=$'\n' read -r -d '' -a RESULTS < <(./printoutput.bash && printf '\0')
# Remove the first element
unset 'RESULTS[0]'
# Just to check that the unset worked
declare -p RESULTS
echo "-----------------------------------------------------------"
# This loops through the array, adding ' before and ', after each value
result=$(printf "'%s'," "${RESULTS[@]}")
# Remove the last ,
finalresult="${result%?}"
echo "$finalresult"
\n
我使用的方法是通过将输出发送到数组来摆脱所有这些。然后打印数组,添加单引号和逗号。然后删除最后一个逗号。
运行第二个脚本会给我你想要的输出:
./secondscript.bash
declare -a RESULTS=([1]="1" [2]="12" [3]="13" [4]="14" [5]="15" [6]="16" [7]="17")
-----------------------------------------------------------
'1','12','13','14','15','16','17'
推荐阅读
- bash - 如何从文本文件中提取行,仅当行以日期开头时
- javascript - vscode:有没有办法对“未链接文件”中的函数使用“转到定义”
- c - 以编程方式获取 Linux 中的 USB 主机控制器参数
- javascript - 无法添加属性 2,对象不可扩展 Array.push
- java - 有没有办法从类路径外部导入规则文件?
- c# - 下载超大文件时连接关闭
- excel - 在一列中查找并替换为 2 列中的数据
- javascript - React:如何将 JSON 对象转换为数组并渲染它?
- asp.net-core - Mediatr 范围问题
- html - 网页上的悬停效果覆盖下拉导航栏