Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminal command equivalent of PHP implode when combining lines

Tags:

bash

terminal

awk

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)
like image 215
Petra Barus Avatar asked Dec 10 '25 19:12

Petra Barus


2 Answers

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
like image 157
Sundeep Avatar answered Dec 13 '25 02:12

Sundeep


#!/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)}'
like image 39
Zombo Avatar answered Dec 13 '25 01:12

Zombo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!