Home > OS >  How to separate every two lines with awk
How to separate every two lines with awk

Time:08-22

I have this file.txt:

     Edward
     Lisa
     James
     Karine
     Jhone
     Kathrine

and i just want to make a skip after each two lines and replace the skips with hyphens (-----)

Output desired:

     Edward
     Lisa
     --------------
     James
     Karine
     --------------
     Jhone
     Kathrine

Thank you

CodePudding user response:

Using GNU sed:

$ sed '3~2i --------------' file.txt
Edward
Lisa
--------------
James
Karine
--------------
Jhone
Kathrine

Starting with the third line, insert a line of dashes before that line and every 2nd line following.

CodePudding user response:

If prefer to try with AWK, i feel this could work and print the name in oneline.

awk '{ if (lastline) {print lastline,$0;lastline=""}else {lastline=$0;next}}'

CodePudding user response:

You can do it simply in awk by keeping a counter and when it reaches 2 output your separator line and reset the counter to zero. Your second rule just prints the current line and increments the counter, e.g.

awk 'n==2 {print "--------------"; n=0} {print; n  }' file

Example Use/Output

With your data in the file named file, the output from the awk command above would be:

Edward
Lisa
--------------
James
Karine
--------------
Jhone
Kathrine
  • Related