I have a couple of lines and want to group the line into 5 and then implode it for MySQL IN () query.
I have made it out until this
awk '{ printf "%s", $0; if (NR % 5 == 0) print ""; else printf " " }
For example, I want these lines below
1
2
3
4
5
6
to be
1,2,3,4,5
6
If I use this
awk '{ printf "%s", $0; if (NR % 5 == 0) print ""; else printf "," }
Then the output will have , in the trailing line if all the lines are not divisible by 5
UPDATE
Previous title is awk instead of bash, but turns out there is more simpler solution than awk. My goal is to do something like this
$seq 12 | pr -7ats, | xargs -I X echo "SELECT * FROM Table IN (X)" #or execute mysql
SELECT * FROM Table WHERE id IN (1,2,3,4,5,6,7)
SELECT * FROM Table WHERE id IN (8,9,10,11,12)
pr is the tool for this
$ seq 6 | pr -5ats,
1,2,3,4,5
6
$ seq 18 | pr -5ats,
1,2,3,4,5
6,7,8,9,10
11,12,13,14,15
16,17,18
#!/usr/bin/awk -f
{
a[NR] = $0
}
END {
for (b in a) {
printf a[b] (b % 5 && b != NR ? "," : RS)
}
}
Or one liner:
awk '{a[NR]=$0} END {for (b in a) printf a[b] (b%5 && b!=NR ? "," : RS)}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With