Geveze
Geveze

Reputation: 401

Empty row after each record and columns in newline

I have a file with variable columns what looks like this:

text11|text12|text13 text121|text122|text123 text131|text132|text133
text21|text22|text23 text221|text222|text223 text231|text232|text233 text241|text242|text243

What I want is that :

  1. each column should be on a new line
  2. pipe should be replaced by space
  3. and after each record of the original file there should be an empty line

like this:

text11  text12  text13 
text121 text122 text123 
text131 text132 text133

text21  text22   text23 
text221 text222 text223
text231 text232 text233
text241 text242 text243

Is there a way to do this with only awk?

I tried something like this:

cat file.txt | awk 'gsub(" ","\n"); gsub("\n", "\n\n",$NR)'

but that does not work of course.

Upvotes: 2

Views: 117

Answers (4)

hek2mgl
hek2mgl

Reputation: 158110

A simple, non idiomatic, approach might be this:

awk '{for(i=1;i<=NF;i++){gsub(/\|/, " ", $i);print $i} print ""}' file

Explanation:

{
    # Iterate through the input fields, which are split by space
    # Note: NF is the number of input fields
    for(i=1; i<=NF; i++) {
        # replace all pipes by space
        gsub(/\|/, " ", $i)
        # and print
        print $i
    }
    # Additional newline
    print "" 
}

Upvotes: 0

James Brown
James Brown

Reputation: 37424

Another, difference probably in gsub(/$/,"\n"):

$ awk '{gsub(/ /,"\n");gsub(/\|/," ");sub(/$/,"\n")}1' file

Output:

text11 text12 text13
text121 text122 text123
text131 text132 text133

text21 text22 text23
text221 text222 text223
text231 text232 text233
text241 text242 text243

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 204164

$ awk -v ORS='\n\n' '{gsub(FS,RS); gsub(/\|/,OFS)} 1' file
text11 text12 text13
text121 text122 text123
text131 text132 text133

text21 text22 text23
text221 text222 text223
text231 text232 text233
text241 text242 text243

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133650

Could you please try following.

awk '{gsub(/\r/,"");gsub(FS,ORS);gsub(/\|/,OFS)} 1'  Input_file

OR

awk '{gsub(/\r/,"");gsub(/ /,ORS);gsub(/\|/,OFS)} 1'  Input_file

OR

awk '{gsub(/\r/,"");gsub(/ /,"\n");gsub(/\|/,OFS)} 1'  Input_file

Explanation: Adding detailed explanation for above code. This is only for explanation purposes.

awk '              ##Starting awk program from here.
{                  ##Starting main BLOCK of program from here.
  gsub(FS,ORS)     ##Globally substituting spaces with new lines here.
  gsub(/\|/,OFS)   ##Globally substituting pipe with space for all occurrences of current line.
}                  ##Closing main BLOCK of this line here.
1                  ##Mentioning 1 will print edited/non-edited lines here.
'  Input_file      ##Mentioning Input_file name here.

Upvotes: 1

Related Questions