Align /etc/hosts File Entries
Align IP addresses and hostnames in /etc/hosts or similar DNS mapping files for easy maintenance.
Detailed Explanation
Formatting Hosts Files
The /etc/hosts file maps IP addresses to hostnames, with fields separated by whitespace (tabs or spaces). As entries accumulate, the file can become messy with inconsistent spacing. Aligning the columns makes it easy to see which IP maps to which hostname.
Before
127.0.0.1 localhost
192.168.1.10 web-server.local
192.168.1.11 db-master.local db-01
192.168.1.12 cache.local redis
10.0.0.1 api-gateway.internal
10.0.0.2 auth-service.internal auth
172.16.0.100 monitoring.corp grafana prometheus
After
127.0.0.1 localhost
192.168.1.10 web-server.local
192.168.1.11 db-master.local db-01
192.168.1.12 cache.local redis
10.0.0.1 api-gateway.internal
10.0.0.2 auth-service.internal auth
172.16.0.100 monitoring.corp grafana prometheus
Steps
- Select Spaces (2+) or Tab as the input delimiter (depending on your file's formatting).
- Set the output delimiter to Spaces.
- Enable Trim whitespace.
- All columns are left-aligned.
Handling Multiple Hostnames
The hosts file allows multiple hostnames per line (aliases). Each additional hostname is treated as an extra column by the aligner, so lines with more aliases will produce more columns. Lines with fewer aliases are padded to maintain alignment.
Comments
Lines starting with # are treated as single-column rows and pass through unchanged. Your existing comments explaining groups of entries will be preserved.
Cross-Platform
This technique works for any hosts-style file:
- Linux/macOS:
/etc/hosts - Windows:
C:\Windows\System32\drivers\etc\hosts - Docker: extra_hosts entries in docker-compose.yml
Use Case
A network administrator maintains a hosts file with 100+ entries across development, staging, and production environments and needs to keep the file organized.