[英]Using Grep to create multiple variables in a loop per line - BASH
我正在尝试采用上述格式的多行文件,并从中制作MySQL插入语句。 最终结果目标类似于输出:-
insert into ansible_db (ip, version) values ("$ip", "$version")
以下数据示例的每行每行(这是输入文件,我需要IP地址和味精段的结果-即4.0.3):-
ok: [192.168.0.214] => {s "msg": "4.0.3"s}
ok: [192.168.0.210] => {s "msg": "4.0.8"s}
ok: [192.168.0.208] => {s "msg": "fdsajkghjfdka"s}
ok: [192.168.0.216] => {s "msg": "Potatoes""""s}
以下信息可以正确获取IP和消息:-
$ip=grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
$version= grep -oP '(?<=\"\: \").*(?=\"s})' #format of the message will vary going forward.
我想将其循环,但是我很挣扎。 任何建议表示赞赏。
在这种情况下,不需要while循环。 如果文件具有与您在问题中提供的结构相同的结构,则以下命令应打印所需的行。
awk -v FS='[][]|"' '{print "insert into ansible_db (ip, version) values ( \""$2 "\" , \""$6"\" )" }' yourInputFile
请注意,以上命令将在标准输出中显示结果,如果要执行,则可以在命令末尾使用|bash
,例如:
awk -v FS='[][]|"' '{print "insert into ansible_db (ip, version) values ( "$2 " , "$6" )" }' yourInputFile |bash
注意, MySql VALUES
语法要求将复杂的字符串参数括在引号中。
若要获取有效的MySql插入语句,请使用以下方法:
awk '{ gsub(/[\[\]]/,"",$2); sub("\"+s}","\"",$6);
print "insert into ansible_db (ip, version) values (\""$2"\", "$6");" }' file
输出:
insert into ansible_db (ip, version) values ("192.168.0.214", "4.0.3");
insert into ansible_db (ip, version) values ("192.168.0.210", "4.0.8");
insert into ansible_db (ip, version) values ("192.168.0.208", "fdsajkghjfdka");
insert into ansible_db (ip, version) values ("192.168.0.216", "Potatoes");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.