2

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
Advil
  • 29

3 Answers3

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"} '
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 09 '18 at 17:16
  • You can replace {print;} with 1; for the same effect. – David Foerster Oct 09 '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.