-2

I am trying to solve one competitive question, where I'm stuck at below scenario can some one help me out to understand how the output can be achieved

Explanation : Every group of three consecutive rows should be folded into one

[ Output is shared below ]

Data in file :

Abc 123,
zyxhj pqr
raj
ram:
vilas, 
1234
jkal
yui
gshj

Output :

Abc 123,zyxhj pqr raj
ram:vilas,1234
jkal yui gshj
αғsнιη
  • 40,939
  • 15
  • 71
  • 114
codeholic24
  • 307
  • 3
  • 15
  • Please search around or show your efforts when trying to solve your problem. In the output, some lines are joined with spaces, some others are not. Why? – Quasímodo Nov 01 '20 at 14:33
  • [How to process a multi column text file to get another multi column text file?](https://unix.stackexchange.com/questions/308631/how-to-process-a-multi-column-text-file-to-get-another-multi-column-text-file) not exact duplicate, but portion of the answers can be used here: – Sundeep Nov 01 '20 at 14:49
  • The last group may be incomplete -- one or two lines? I would expect xargs and paste to correctly terminate the short output line, and awk to leave it without a newline (it would need an END block for that case). – Paul_Pedant Nov 01 '20 at 15:53

1 Answers1

2

Using xargs:

xargs -d'\n' -n3 <infile

read and print every 3 lines according to the \newline as delimiter


Using paste:

paste -d ' ' - - - <infile

paste data in 3 columns with space delimiter


Using awk:

awk '{ printf "%s%s", $0, (NR%3?OFS:ORS) }' infile

printf every line and then print OFS (Output Field Separator; space by default) if NR (Number of Record) was not module of 3 else ORS (Output Record Separator; newline by default) if it was.

αғsнιη
  • 40,939
  • 15
  • 71
  • 114
  • Oh indeed, last 3 lines don't match the behaviour of previous – A.B Nov 01 '20 at 13:06
  • @αғsнιη I used `paste -d - - -` this as work for me – codeholic24 Nov 01 '20 at 14:17
  • 1
    Also, as you already do the good conditional, you could do this alternative: `awk '{ORS = (NR%3 ? OFS : "\n") }1' file` (which allows someone to forget `printf` secret issues temporarily) – thanasisp Nov 01 '20 at 21:05
  • @thanasisp [that](https://unix.stackexchange.com/questions/617431/how-every-group-of-n-consecutive-rows-are-folded-into-one-and-separated-by-tab/617435?noredirect=1#comment1155031_617435)'s also nice! – αғsнιη Nov 01 '20 at 21:13