Reputation: 253
There is a file which contains data in a 'n*1'
format:
1
2
3
4
5
6
Is there any way to convert it to a 'n*3'
format like:
1,2,3
4,5,6
via awk
rather than using for loop
?
Really no idea about this..Any help or key word is appreciated.
Upvotes: 3
Views: 773
Reputation: 185025
Try this:
awk 'NR%3==0{print;next}{printf "%s,",$0}' file
or decomposed :
NR%3==0 # condition, modulo 3 == 0
{print;next} # then print and skip to the first line
{printf "%s,",$0} # printf to not print newlines but current int + ,
Upvotes: 1
Reputation: 113834
$ awk '{printf "%s%s",$0,(NR%3==0?ORS:",")}' File
1,2,3
4,5,6
The command printf "%s%s",$0,(NR%3==0?ORS:",")
tells awk to print two strings. The first is $0
which is the current line. The second string is NR%3==0?ORS:","
which is either ORS the output record separator (if the line number is a multiple of three) or else ,
for all other line numbers.
$ sed 'N;N;s/\n/,/g' File
1,2,3
4,5,6
By default, sed reads in each line from the file one by one. N
tells sed to read in another line, appending the line to the current one, separated by a newline. N;N
tells sed to do that twice so that we have a total of three lines in the pattern space. s/\n/,/g
tells sed to replace those two separator newlines with commas. The result is then printed.
The above assumes that we are using GNU sed. With minor modifications, this can be made to work with BSD/OSX sed.
Upvotes: 3
Reputation: 92854
The most simple one - paste
command:
paste -d, - - - <file
The output:
1,2,3
4,5,6
Upvotes: 2
Reputation: 133458
Following may help you on same.
xargs -n3 < Input_file | sed 's/ /,/g'
Upvotes: 1