How to Sort Text Lines Online
Common Needs for Line Sorting
Many work scenarios require sorting text lines: organizing glossaries or terminology lists (alphabetically); arranging programming import statements; sorting CSS properties for readability; organizing name lists or contact lists; sorting log lines chronologically; converting unordered lists to ordered format for documents or reports.
Types of Sorting
- Alphabetical (ascending A-Z): most common, sort lines from A to Z by first character
- Alphabetical (descending Z-A): reverse alphabetical order
- Numerical sort: treat lines as numbers (avoids string comparison making 10 sort before 2)
- Random sort (shuffle): randomly shuffle lines, useful for draws or randomizing lists
- Sort by line length: from shortest to longest or reverse
- Reverse order: completely reverse the current line order
Case Sensitivity
Case sensitivity is an important detail in text sorting. Case-sensitive sorting places all uppercase letters before lowercase (because uppercase letters have smaller ASCII code values). Case-insensitive sorting ignores case differences in comparisons โ apple and Apple are treated as equal. For most list organization scenarios, case-insensitive sorting is more intuitive and is the recommended default.
Sorting with Command Line
In Unix/Linux/macOS systems, the sort command is a powerful tool for text line sorting:
# ๅบๆฌๅญๆฏๆๅบ
sort input.txt
# ๅๅๆๅบ
sort -r input.txt
# ๆฐๅญๆๅบ
sort -n input.txt
# ๅฟฝ็ฅๅคงๅฐๅๆๅบ
sort -f input.txt
# ๅ ้ค้ๅค่กๅนถๆๅบ
sort -u input.txt
# ๆ็ฌฌไบๅๆฐๅญๆๅบ๏ผtab ๅ้๏ผ
sort -t$'\t' -k2 -n input.txt
Python Code Implementation
# ่ฏปๅๆไปถๅนถๆๅญๆฏ้กบๅบๆๅบ
with open('input.txt', 'r') as f:
lines = f.readlines()
# ๅป้ค็ฉบ่กๅนถๆๅบ๏ผๅฟฝ็ฅๅคงๅฐๅ๏ผ
sorted_lines = sorted(
[l.strip() for l in lines if l.strip()],
key=str.lower
)
# ๅๅ
ฅ็ปๆ
with open('output.txt', 'w') as f:
f.write('\n'.join(sorted_lines))
Special Considerations for Chinese Sorting
Chinese character sorting is more complex than English. Common approaches: sort by Unicode code point (not intuitive for humans), sort by pinyin (most natural for dictionaries and name lists), sort by stroke count (common in formal documents). Online tools typically provide Unicode sorting; pinyin sorting requires dedicated Chinese word segmentation and pinyin conversion libraries. In Python, the pypinyin library enables pinyin-based sorting.
Handling Prefixes and Special Characters
If list lines have uniform prefixes (like bullet points - or *, or numbering 1. 2. 3.), remove these prefixes before sorting and re-add them after. Otherwise the sort is based on prefix characters rather than actual content. This preprocessing typically requires regular expressions to extract pure content before sorting.
Try the free tool now
Use Free Tool โ