-2

I have a data as:

q   
w   
e

e
r
r t

23
21
1

Whenever we find blank line change it to new column.

Output

q,e,23    
w,r,21
e,r,1
,t,

I have tried but neither with sed nor I am able to change the row. Please let me know how can we achieve this.

amit10504
  • 17
  • 5
  • You say "Whenever we find blank line change it to new row." but what you are showing seems to be what you get when you change to a new column at blank lines, while filling rows. – Kusalananda Sep 18 '20 at 07:20
  • @Kusalananda Sorry My mistake I have edit the question once again – amit10504 Sep 18 '20 at 07:25

4 Answers4

0

I can recommend awk. You can set the row separator to an empty line, and collect the rows into the variables. At the END you can pront the collected variables.

Something like this:

awk 'BEGIN{RS="\n\n";}{A=(A","$1);B=(B","$2);C=(C","$3);D=(D","$4)}END{print A;print B;print C;print D}' input.txt |sed s/'^,'//

But the princip remains. In fact it is the table transposition.

schweik
  • 1,250
  • You should mention that's relying on non-POSIX functionality for multi-char RS and so what that does will vary depending on your awk version. – Ed Morton Sep 18 '20 at 15:42
0

One option is to replace all newlines with commas (since you seem to want CSVs in the end), then replace double commas with a newline and delete repetetive spaces. In the end transpose the result with datamash:

tr '\n' ',' < input.dat  |
  sed 's/,,/\n/g' |
  tr -d ' ' |
  datamash --no-strict --filler='' -t ',' transpose
FelixJN
  • 13,566
  • tr '\n' ',' converts it's input into a non-text file per POSIX (no terminating newline) and so YMMV with what any text-processing tool might do with that afterwards. – Ed Morton Sep 18 '20 at 15:52
0

Using GNU awk, which has true multidimensional arrays, and a "join" function as an external library:

gawk '
    @include "join"
    BEGIN {row=0; col=0}
    NF == 0 {col++; row=0; next}
    {data[row][col] = $1; row++}
    END {
        PROCINFO["sorted_in"] = "@ind_num_asc"
        for (r in data)
            print join(data[r], 0, col, ",")
    }
' file

outputs

q,e,23
w,r,21
e,r,1
,t,
glenn jackman
  • 85,964
0
$ cat tst.awk
BEGIN {
    OFS = ","
    numCols = 1
}
!NF {
    rowNr = 0
    ++numCols
    next
}
{
    vals[++rowNr,numCols] = $0
    numRows = (rowNr > numRows ? rowNr : numRows)
}
END {
    for (rowNr=1; rowNr<=numRows; rowNr++) {
        for (colNr=1; colNr<=numCols; colNr++) {
            printf "%s%s", vals[rowNr,colNr], (colNr<numCols ? OFS : ORS)
        }
    }
}

$ awk -f tst.awk file
q,e,23
w,r,21
e,r,1
,t,
Ed Morton
  • 31,617