2

This question already has an answer here:

I want to add a new line every four lines of a document.

For example:

abc
def
ghi
jkl
mno
pqr
stu
vw
xyz

should become:

abc
def
ghi
jkl

mno 
pqr
stu
vw

xyz

marked as duplicate by sebasth, fedorqui, RalfFriedl, Jeff Schaller, αғsнιη Oct 9 '18 at 18:52

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

12

sed (GNU)

sed '0~4G'

man sed explains ~ as:

first ~ step
Match every step'th line starting with line first. For example, ``sed -n 1~2p'' will print all the odd-numbered lines in the input stream, and the address 2~5 will match every fifth line, starting with the second. first can be zero; in this case, sed operates as if it were equal to step. (This is an extension.)

sed (other)

Short (ugly for 100 lines):

sed 'n;n;n;G'

Or, Count new lines:

sed -e 'p;s/.*//;H;x;/\n\{4\}/{g;p};x;d'

Or, to be more portable, written as (remove comments for some versions of sed) :

sed -e '             # Start a sed script.
         p            # Whatever happens later, print the line.
         s/.*//       # Clean the pattern space.
         H            # Add **one** newline to hold space.
         x            # Get the hold space to examine it, now is empty.
         /\n\{4\}/{   # Test if there are 4 new lines counted.
             g        # Erase the newline count.
             p        # Print an additional new line.
           }          # End the test.
         x            # match the `x` done above.
         d            # don't print anything else. Re-start.
       '              # End sed script.

awk

Probably:

awk '1 ; NR % 4 == 0 {printf"\n"} '
  • 1
    @KonradRudolph A s/older/other/ done, Better? – Isaac Oct 9 '18 at 19:58
10

try this command:

awk ' {print;} NR % 4 == 0 { print ""; }'
  • In case you want to understand what the above is doing: awk will process your file line by line. It will print each line. If the line number NR is divisible by 4 with no remainder (% 4 == 0) then print a blank line – Neil McGuigan Oct 9 '18 at 17:16
  • You can replace {print;} with 1; for the same effect. – David Foerster Oct 9 '18 at 17:57
1
 sed -e 'n;n;n;G'

 perl -pe '$. % 4 or s/$/\n/' 

 perl -lpe '$\ = $. % 4 ? "\n"  : "\n\n"' 

Where we change the output record separator every fourth line.

  • the sed one assumes the input has a number of line that is multiple of 4 (or that you're using GNU sed and POSIXLY_CORRECT is not in the environment). You should use sed 'n;n;n;G' here. – Stéphane Chazelas Oct 9 '18 at 11:11
  • Yes that is correct, hadn't realized it. – Rakesh Sharma Oct 9 '18 at 13:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.