3

I would like to take the output of a bash command (in this case grep) and insert a blank line every other line:

not
like
this ...

but

like

this!

Smart way to do it in bash?

0

5 Answers 5

8

There are many ways to do this for text files. The simplest is probably

$ sed G filename
5

Using pr from coreutils:

$ grep '' file | pr -Td
not

like

this ...

(note that this does double-space the final line - unlike, say, sed '$!G'). From man pr:

   -d, --double-space
          double space the output

   -T, --omit-pagination
          omit page headers and trailers, eliminate any pagination by form
          feeds set in input files
3

Starting with a file like:

$ cat >file
not
like
this ...

sed will work:

$ sed 's/$/\n/' file
not

like

this ...

So will awk:

$ awk 1 ORS='\n\n' file
not

like

this ...

1 is awk's cryptic shorthand for print-the-line and ORS='\n\n' tells awk to separate output lines with not just one but two newlines.

More

A shorter sed command, as suggested by steeldriver, is:

sed '$!G' file

The G command appends a newline and the hold space to the end of the pattern space. Since, by default, the hold space is empty, this has the effect of just adding an extra newline at the end of each line. The prefix $! tells sed to do this on all lines except the last one.

0
1

Another awk version:

| awk '{print $0, "\n"}'
-1
Test
10
20
30

Output
perl -pe "s/$/\n/" test 
10

20

30

Not the answer you're looking for? Browse other questions tagged .