neversaint neversaint - 5 months ago 11
Linux Question

Converting lines in chunks into tab delimited

I have the following lines in 2 chunks (actually there are ~10K of that).
And in this example each chunk contain 3 lines. But actually it 6 lines.

xox
91-233
chicago

koko
121-111
alabama


I want to turn it into

xox 91-233 chicago
koko 121-111 alabama


How can I do that?

I tried
tr "\n" "\t"
but doesn't do what I want.

Answer
$ awk -F'\n' '{$1=$1} 1' RS='\n\n' OFS='\t' file
xox     91-233  chicago
koko    121-111 alabama 

How it works

Awk divides input into records and it divides each record into fields.

  • -F'\n'

    This tells awk to use a newline as the field separator.

  • $1=$1

    This tells awk to assign the first field to the first field. While this seemingly does nothing, it causes awk to treat the record as changed. As a consequence, the output is printed using our assigned value for ORS, the output record separator.

  • 1

    This is awk's cryptic shorthand for print the line.

  • RS='\n\n'

    This tells awk to treat two consecutive newlines as a record separator.

  • OFS='\t'

    This tells awk to use a tab as the field separator on output.

Comments