1

I have a file that looks like the following

1
1
1
1
1
1
12
2
2
2
2
2
2
2
3
4

What I want to do is convert this column in multiple rows. Each new line/row should start after 5 entries, so that the output will like like this

1 1 1 1 1
1 12 2 2 2
2 2 2 2 3
4

I tried to achieve that by using

awk '{printf "%s" (NR%5==0?"RS:FS),$1}' file

but I get the following error

awk: line 1: runaway string constant "RS:FS),$1} ...

Any idea on how to achieve the desired output?

Thanos
  • 594
  • 2
  • 7
  • 28
  • Theres a double quote before RS. – 123 Feb 10 '16 at 11:06
  • @123 Thanks for your comment! This was it!!! HOwever since I am not quite familiar with `awk`, what was the problem there? To be quite frank, I am not certain about the `printf "%s" (NR%5==0?"RS:FS),$1` command either;I just found it on SE. Could you post an answer, explaining the command sequence? – Thanos Feb 10 '16 at 11:10

3 Answers3

2

Maybe this awk one liner can help.

awk '{if (NR%5==0){a=a $0" ";print a; a=""} else a=a $0" "}END{print}' file

Output:

1 1 1 1 1
1 12 2 2 2
2 2 2 2 3
4

Longer awk:

{
    if (NR%5==0)
    {
       a=a $0" ";
       print a;
       a="";
    }
    else
    {
       a=a $0" ";
    }
 }
 END
 {
    print
 }
Firefly
  • 449
  • 5
  • 20
1

Slightly different approach, still using awk:

$ awk '{if (NR%5) {ORS=""} else {ORS="\n"}{print " "$0}}' input.txt
 1 1 1 1 1
 1 12 2 2 2
 2 2 2 2 3
 4

Using perl:

$ perl -p -e 's/\n/ / if $.%5' input.txt
1 1 1 1 1
1 12 2 2 2
2 2 2 2 3
4 
Fredrik Pihl
  • 44,604
  • 7
  • 83
  • 130
0

No need to complicate...

$ pr -5ats' ' <file

1 1 1 1 1
1 12 2 2 2
2 2 2 2 3
4
karakfa
  • 66,216
  • 7
  • 41
  • 56