I'm trying to take a multiline file in the above format and make MySQL insert statement from it. End result aim is something similar to outputting: -
insert into ansible_db (ip, version) values ("$ip", "$version")
per line for each of the following data examples (this is the input file, I want the IP address and the result of the msg segment - ie 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}
The following greps get the IP's and message out appropriately: -
$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.
I want to put it in a loop, but I'm struggling. Any advice appreciated.
In this case, while-loop is not required. If your file is having the consistent structure like you provided in the question following command should print the required lines.
awk -v FS='[][]|"' '{print "insert into ansible_db (ip, version) values ( \""$2 "\" , \""$6"\" )" }' yourInputFile
Note that above command will display the result in std out, if you want to execute then you can use |bash
in the end of the command like:
awk -v FS='[][]|"' '{print "insert into ansible_db (ip, version) values ( "$2 " , "$6" )" }' yourInputFile |bash
Note, MySql VALUES
syntax requires complex string arguments to be enclosed with quotes.
To obtain valid MySql insert statements use the following approach:
awk '{ gsub(/[\[\]]/,"",$2); sub("\"+s}","\"",$6);
print "insert into ansible_db (ip, version) values (\""$2"\", "$6");" }' file
The output:
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");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.