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?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityThere are many ways to do this for text files. The simplest is probably
$ sed G filename
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
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.
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.