When you download raw data files or source code from legacy systems, the spacing is often formatted using hidden “Tab” characters instead of standard spaces. This is a massive problem when moving files between different text editors, because one editor might render a Tab as 4 spaces, while a different IDE might render it as 8 spaces, completely destroying the visual alignment of the code. To instantly sanitize a file and convert all hidden tabs into hardcoded, absolute space characters, you must use the expand command.
How the expand Command Works
The expand command is a highly specific text manipulation utility designed to hunt down the invisible ASCII Tab character and replace it with a predetermined number of standard spacebar characters.
By default, if you run the command against a file, it will assume every single Tab character should be converted into exactly 8 spaces.
expand source_code.py
The command will read the Python file, replace the tabs, and print the resulting space-formatted text directly to your terminal screen. The original file remains untouched. To save the sanitized output into a brand new, permanent file, use the bash redirection operator (>):
expand source_code.py > clean_code.py
Setting Custom Tab Stops
While 8 spaces might be standard for legacy Unix systems, modern web development almost exclusively uses a 2-space or 4-space indentation standard. You can explicitly define exactly how many spaces should replace a single tab by using the -t (tabs) flag.
To forcefully convert every tab into exactly 4 standard spaces, run:
expand -t 4 source_code.py > clean_code.py
This ensures the code’s visual indentation will look identical on every single computer, regardless of what text editor the developer is using.
Only Expanding Initial Indentations
If you are working with a highly complex data file (like a TSV or Tab-Separated Values database), you only want to convert the tabs at the very beginning of the lines (the code indentation). If you convert the tabs located in the absolute middle of the lines, you will completely destroy the database structure.
To protect the structural integrity of the file, append the -i (initial) flag.
expand -i -t 4 script.sh
This command instructs expand to only target the tabs located at the far left edge of the screen (the indentations). The exact moment it encounters a standard letter or number, it will immediately stop converting, leaving any tabs buried deeper inside the line perfectly intact.