将制表符分隔的字符串转换为bash中的SQL查询

时间:2018-01-28 21:41:30

标签: string bash command-line debian-based string-operations

我有一个doveadm命令输出,由制表符分隔,如下所示:

Username        Quota name      Type    Value   Limit   %
user2@example2.com    User quota      STORAGE 203032  1024000 19
some@example.com    User quota      MESSAGE 816     -       0
other@ex.com    User quota      STORAGE 116873  1024000 11
email@ex.com    User quota      MESSAGE 235     -       0

如何将每一行转换为SQL查询?

INSERT INTO quota (username, quota, type, value, limit, percentage) VALUES ('user2@example2.com', 'User quota', 'STORAGE', 203032, 1024000, 19);
...

1 个答案:

答案 0 :(得分:1)

我会用awk说:

awk -F'\t' 'NR > 1 {printf "INSERT INTO quota (username, quota, type, value, limit, percentage) VALUES (\047%s\047, \047%s\047, \047%s\047, %d, %d, %d);\n", $1, $2, $3, $4, $5, $6}' file

结果如下:

INSERT INTO quota (username, quota, type, value, limit, percentage) VALUES ('user2@example2.com', 'User quota', 'STORAGE', 203032, 1024000, 19);
INSERT INTO quota (username, quota, type, value, limit, percentage) VALUES ('some@example.com', 'User quota', 'MESSAGE', 816, 0, 0);
INSERT INTO quota (username, quota, type, value, limit, percentage) VALUES ('other@ex.com', 'User quota', 'STORAGE', 116873, 1024000, 11);
INSERT INTO quota (username, quota, type, value, limit, percentage) VALUES ('email@ex.com', 'User quota', 'MESSAGE', 235, 0, 0);

希望这有帮助。