โ† Back to Blog

How to Sort Text Lines Online

2026-04-03 ยท 5 min read

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

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 โ†’