Reputation: 401
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 :
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
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
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
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
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