I have a bunch of text files, some of which contain lines that are empty, i.e. only consist only of a newline, or possible spaces followed by a newline. I locate the files using a find
command.
- Example file
#Title 1 12345678 1234
#Title 2 12345678 1234 12345678 1234
- Expected output
#Title 1 12345678 1234 #Title 2 12345678 1234 12345678 1234
I want to remove all such empty lines. I tried it with the following command on Debian Linux Stretch:
cat "/path/to/file" | sed '/^\s*$/d' | sponge "/path/to/file";
Some of the files had for example 4 or more trailing blank lines, but the above command only removed all but one of the trailing blank lines.
How could I remove this last trailing blank line? As mentioned: should there be any blank lines further up in the file then these should be removed also.
I am trying to get some consistency between the files as the files are stored in an array of sorts within a BASH variable. The files are then looped over and all the blank lines and trailing blank lines are removed, while some of the files already don't have blank lines or any trailing blank line.
sed
versions have a-i
flag that allows changing the file in place, so you won't need pipes, just:sed -i '/^\s*$/d' /path/to/file
. – aviro Nov 08 '22 at 07:24sed
command should work. And it does work when I run it on my machine. What is the actual result of yoursed
command? From what I understand, you're saying that there's always one blank line left in the output, no matter how many blank lines there are in the file? For instance, if there's only one blank line, does it get removed? If there are 2? 3? 10? Always one blank line is not removed? On any file? – aviro Nov 08 '22 at 07:54sed
they are using. Some implementations may delete lines that contain zero or mores
characters. The\s
pattern is definitely not standard. This would explain why empty lines are removed while lines with only spaces or tabs would still be kept. – Kusalananda Nov 08 '22 at 07:58s
characters. The lines that are not removed may contain spaces. – Kusalananda Nov 08 '22 at 08:07s
character, it's not a blank line. A blank line won't include any character. – aviro Nov 08 '22 at 08:19sed
does not understand\s
as a space character, it may understand it as ans
. The pattern would then match lines consisting of zero or mores
characters (which includes empty lines, but not lines containing spaces). – Kusalananda Nov 08 '22 at 08:24