Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
941 views
in Technique[技术] by (71.8m points)

bash - Terminal command equivalent of PHP implode when combining lines

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...