Sai
Sai

Reputation: 67

Replacing newlines with commas at every third occurrence using AWK?

For example: a given file has the following lines:

1
alpha
beta
2
charlie
delta
10
text
test

I'm trying to get the following output using awk:

1,alpha,beta  
2,charlie,delta  
10,text,test  

Upvotes: 2

Views: 270

Answers (4)

user4401178
user4401178

Reputation:

You can also use xargs with sed to coalesce multiple lines into single lines, useful to know:

cat file|xargs -n3|sed 's/ /,/g'

Upvotes: 0

karakfa
karakfa

Reputation: 67507

there is a tool for this kind of text processing pr

$ pr -3ats, file

1,alpha,beta
2,charlie,delta
10,text,test

Upvotes: 0

Spade
Spade

Reputation: 2280

Fairly simple. Use the output record separator as follows. Specify the comma delimiter when the line number is not divisible by 3 and the newline otherwise:

awk 'ORS=NR%3?",":"\n"' file

Upvotes: 1

anubhava
anubhava

Reputation: 785176

awk can handle this easily by manipulating ORS:

awk '{ORS=","} !(NR%3){ORS="\n"} 1' file

1,alpha,beta
2,charlie,delta
10,text,test

Upvotes: 0

Related Questions