![banner](banner2.png)
For a list of BASHing data 2 blog posts see the index page.
Line spacing tricks - updated
The 3-line file used in this post is called "snip":
aaa
bbb
ccc
The tricks shown in this post are the easiest ones I know. There are other ways to do these jobs on the command line, but they're not so simple. An interesting but not-so-simple AWK command is shown in the Footnote.
Adding a line space. Adding one blank line between existing lines is "double-spacing" and is most easily done with sed G:
![spacing1](img2/2024-07-12_1.png)
As you can see, sed adds a blank line after every line, including the last. How to delete that trailing blank line? Three easy ways are to delete the last byte (the last newline character) with head, delete the last line with sed, or echo the sed G output:
![spacing2](img2/2024-07-12_2.png)
----------------------------------------------------
UPDATE: Reader Tim Chase suggested a better way to add the line spacing with sed, but not after the last line:
![spacing2a](img2/2024-07-12_2a.png)
The command sed '$!G' applies the "G" command to all lines that are not (!) the last line ($). In the screenshot below I'm adding a line space to lines that aren't line 2:
![spacing2b](img2/2024-07-12_2b.png)
The same idea works with adding multiple line spaces (next section of this post), for example:
sed '$!{G;G;G;}' snip
----------------------------------------------------
AWK can do double-spacing by printing every line (the default action) and an empty line, but sed G is quicker to type and the AWK command again builds a trailing blank line:
![spacing3](img2/2024-07-12_3.png)
Adding multiple line spaces. Repeating the sed "G" option will do this job easily, as will setting the output record separator (ORS) in AWK to one more than the desired number of newlines. Below, I'm "triple-spacing" — 2 blank lines after every line — and in the AWK command the ORS is set in a "pseudo-argument":
![spacing4](img2/2024-07-12_4.png)
To delete all trailing blank lines simply, I'd use echo; for example:
![spacing5](img2/2024-07-12_5.png)
Removing line spaces. To delete all genuinely blank lines, the two easiest commands to use are awk NF and grep:
![spacing6](img2/2024-07-12_6.png)
To replace multiple blank lines with a single blank line, the simplest command is cat -s:
![spacing7](img2/2024-07-12_7.png)
Footnote
This AWK command can do double- or triple-spacing without trailing blank lines:
awk -v ORS="\n\n" 'NR>1 {print x} {x=$0} END {printf("%s\n",$0)}' snip
awk -v ORS="\n\n\n" 'NR>1 {print x} {x=$0} END {printf("%s\n",$0)}' snip
![spacing8](img2/2024-07-12_8.png)
The command can be saved as a function, for example
2space() { awk -v ORS="\n\n" 'NR>1 {print x} {x=$0} END {printf("%s\n",$0)}' "$1"; }
![spacing9](img2/2024-07-12_9.png)
Last update: 2024-09-03
The blog posts on this website are licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License