mysql - awk脚本调整格式

标签 mysql bash shell scripting awk

我正在尝试使用以下 awk 脚本对名为 file.txt 的文件中的每 1000 条记录进行计数,并将这些记录括在括号内

file.txt的内容

12345

23456

43567

awk '{ printf $0 " " } NR%1000 == 0 { print "" }' file.txt | sed 's/.*/(&)/'

输出

(12345 23456 43567)

我需要将此输出与mysql批量删除语句相关联,如下所示

Delete from ReportingDetail where ReportingDetailID IN (12345,23456,43567); 
  1. 我无法添加“从 ReportingDetail 中删除”,其中 ReportingDetailID IN”添加到每行的末尾。
  2. 我无法在记录之间添加“,”。

非常感谢您的帮助!

最佳答案

您只能使用 sed 来执行此操作:

sed -e 's/ /,/g' -e 's/^/Delete from ReportingDetail where ReportingDetailID IN (/' -e 's/$/)/' file.txt

例如:

$ echo "1 2 3"|sed -e 's/ /,/g' -e 's/^/Delete from ReportingDetail where ReportingDetailID IN (/' -e 's/$/)/'
Delete from ReportingDetail where ReportingDetailID IN (1,2,3)

编辑 - 对于您的更新(即当您在不同行上有数字时),只需在前面添加您已有的内容即可:

awk '{ printf $0 " " } NR%1000 == 0 { print "" }' file.txt | sed -e 's/ /,/g' -e 's/^/Delete from ReportingDetail where ReportingDetailID IN (/' -e 's/,$/)/'

例如:

$ echo -e "1\n2\n3"|awk '{ printf $0 " " } NR%1000 == 0 { print "" }'|sed -e 's/ /,/g' -e 's/^/Delete from ReportingDetail where ReportingDetailID IN (/' -e 's/,$/)/'
Delete from ReportingDetail where ReportingDetailID IN (1,2,3)

你也可以不使用 awk 来做到这一点,如下所示:

$ echo -e "1\n2\n3\n4"|tr "\n" " "|sed -e 's/ /,/g' -e 's/^/Delete from ReportingDetail where ReportingDetailID IN (/' -e 's/,$/)/'
Delete from ReportingDetail where ReportingDetailID IN (1,2,3,4)

请注意,我使用的 echo 仅用于测试,即它产生的结果是:

$ echo -e "1\n2\n3\n4"
1
2
3
4

关于mysql - awk脚本调整格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9612610/

相关文章:

linux - 在 bash 中循环遍历文件中的行,而不使用标准输入

mysql - mysql 的 Django BooleanField 默认值

php - 无法删除mysql中的行

php - 如何将以逗号分隔的多个值输入到表中?

mysql - 检索 User_ID 在 12 月而非 1 月进行交易的记录

linux - 如何将参数传递给 source 命令调用的脚本?

linux - 使用 sed 或 awk 将某些行中的换行符替换为空格

shell - Tmux 将窗口重命名为当前目录

linux - shell 脚本 : Hexadecimal Loop

linux - 不包含字符串的处理行和匹配行下方的输出行