awk脚本调整格式

时间:2012-03-08 03:48:07

标签: 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“到每一行的birnining。
  2. 我无法在记录之间添加“,”。
  3. 非常感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

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

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

E.g:

$ 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/,$/)/'

E.g:

$ 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 -e "1\n2\n3\n4"
1
2
3
4