Removing empty lines in code and editors
# Remove empty and whitespace-only lines
grep -v '^[[:space:]]*$' file.txt
sed '/^[[:space:]]*$/d' file.txt
# Squeeze repeated blank lines into one
cat -s file.txt
text = open("file.txt").read()
cleaned = "\n".join(line for line in text.splitlines() if line.strip())
const cleaned = text.split(/\r?\n/).filter((line) => line.trim() !== '').join('\n');
// Or keep one blank line between paragraphs
const squeezed = text.replace(/\n\s*\n(\s*\n)+/g, '\n\n').trim();
In VS Code, open Find and Replace, turn on regex (Alt+R), search for ^\s*\n and replace with
nothing. In Vim, :g/^\s*$/d does the same.
Lines broken in the middle of sentences? Remove line breaks joins them. Extra spaces inside lines? Remove whitespace collapses them.
Frequently asked questions
What counts as an empty line?
By default, a line with nothing on it or only spaces and tabs. Such lines look empty but trip up a simple check for an empty string, which is why grep -v "^$" often leaves some behind. Untick the option to remove only lines that are truly empty.
Can I keep paragraph breaks?
Yes. Choose “Keep one between blocks”: runs of several blank lines are squeezed into one, so paragraphs stay separated but the big gaps disappear. Blank lines at the very start and end are removed either way.
Why does text copied from a website or PDF have so many blank lines?
Web pages are built from blocks (paragraphs, divs, list items), and browsers often add a blank line around each when copying. PDFs store text as positioned lines, so copying can add a line break at every visual line and extra ones between blocks. Use remove line breaks to join lines that were broken in the middle of a sentence.
Does it handle Windows line endings?
Yes. \r\n (Windows), \n (macOS and Linux) and old Mac \r line endings are all recognised. The result uses \n.