23

I've got an input file like this:

line 1
line 2
line 3
line 4
line 5
line 6

I'd like to use awk to insert a blank line every few lines; for example, every two:

line 1
line 2

line 3
line 4

line 5
line 6

How can I get awk to put a blank line into my file every n lines?

icktoofay
  • 126,289
  • 21
  • 250
  • 231

5 Answers5

28

A more "awk-ish" way to write smcameron's answer:

awk -v n=5 '1; NR % n == 0 {print ""}'

The "1;" is a condition that is always true, and will trigger the default action which is to print the current line.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • Same here, no? print line and print newline would need to be reversed, otherwise the newline is print before every 5th line instead of after it. – Scrutinizer Mar 15 '13 at 08:51
  • 3
    I would probably write that as `'{print} NR % n == 0 { print "" }`, but that is purely a style issue. – Vatine Sep 03 '13 at 00:34
19
awk '{ if ((NR % 5) == 0) printf("\n"); print; }'

for n == 5, of course. Substitute whatever your idea of n is.

zakkak
  • 1,861
  • 1
  • 19
  • 26
smcameron
  • 1,307
  • 8
  • 8
  • If n=1, the following seem to work: `awk '{print; printf("\n");}'` or simply `awk '{print; print "";}'` – Asclepius Sep 21 '12 at 18:35
  • This will put the first new line before the 5th line instead of after is. print and the printf need to be reversed.. – Scrutinizer Mar 15 '13 at 08:50
7

More awkishness:

awk 'ORS=NR%5?RS:RS RS'

For example:

$ printf "%s\n" {1..12} | awk 'ORS=NR%5?RS:RS RS'
1
2
3
4
5

6
7
8
9
10

11
12
Scrutinizer
  • 9,608
  • 1
  • 21
  • 22
5
awk '{print; if (FNR % 5 == 0 ) printf "\n";}' your_file

I guess 'print' should be before 'printf', and FNR is more accurate for your task.

Devin Burke
  • 13,642
  • 12
  • 55
  • 82
Joyer
  • 371
  • 2
  • 9
2
$ awk -v n=5 '$0=(!(NR%n))?"\n"$0:$0'

If you want to change 'n', please set the parameter 'n' by awk's -v option.

Hirofumi Saito
  • 321
  • 1
  • 5