Tools / Trim whitespace on each line
Trim Spaces and Tabs on Each Line
Remove leading and trailing spaces and tabs from every line. The usual fix for values that will not match.
How it works
Trailing spaces are invisible and they break things. A value pasted from a spreadsheet often carries a trailing space, so "Kathmandu " does not equal "Kathmandu" in a database, a lookup formula or a shell comparison. The result is a mystery that takes an hour to find, because both values look identical on screen.
This tool trims each line from both ends. It removes ordinary spaces and tabs, but it deliberately leaves spaces inside the line alone, so New Baneshwor keeps its space and becomes New Baneshwor rather than NewBaneshwor. If you need to collapse repeated internal spaces, use a find-and-replace, because collapsing inside text changes meaning more often than trimming at the edges does.
Edge cases
- Only the edges of each line are trimmed; internal spaces are preserved.
- Tabs are removed as well as spaces, which fixes values pasted out of columns.
- Non-breaking spaces are not treated as ordinary whitespace by every browser, so a stubborn value may need a targeted replace.
Do it in code instead
The same result with a shell one-liner or a few lines of Python, if you would rather automate it:
Bash (sed)
sed 's/^[[:space:]]*//; s/[[:space:]]*$//' list.txt
Python
print('\n'.join(l.strip() for l in open('list.txt').read().splitlines()))
JavaScript
text.split('\n').map(l => l.trim()).join('\n');
Excel
=TRIM(A1)
Questions
- Does it remove spaces between words?
- No. It only removes whitespace at the start and end of each line. Words keep their internal spacing, which is what you want for names, addresses and sentences.
- Why does Excel TRIM behave differently?
- Excel TRIM also collapses runs of internal spaces to a single space, which is more aggressive than an edge trim. If you are matching Excel output, be aware it changes the middle of the string too.
- Will it fix a trailing carriage return?
- Yes. Line endings are normalised to a single line break before trimming, so a CRLF file does not leave a stray carriage return at the end of each line.