You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对字段无固定宽度的TXT文件按分数降序排序?

Got it, this is a common headache when dealing with delimited text where field lengths vary—luckily, there are straightforward ways to target the Score field without relying on fixed positions. Here are two reliable approaches depending on your preference:

Python Script Solution (Cross-Platform)

If you prefer a scriptable, easy-to-modify solution that works on Windows, macOS, or Linux, Python is perfect for this. It lets you explicitly target the last field (Score) regardless of how long the name/email are:

# Replace 'your_input.txt' with your actual file name
with open('your_input.txt', 'r') as input_file:
    # Read all lines, skipping any empty ones (optional but helpful)
    lines = [line.strip() for line in input_file if line.strip()]

# Sort lines by the Score field (last element after splitting on '|')
# We strip whitespace from the Score and convert to integer for proper numeric sorting
sorted_lines = sorted(
    lines,
    key=lambda line: int(line.split('|')[-1].strip()),
    reverse=True  # Sort from highest to lowest score
)

# Write the sorted result to a new file
with open('sorted_scores.txt', 'w') as output_file:
    output_file.write('\n'.join(sorted_lines) + '\n')

How this works:

  • line.split('|') breaks each line into a list using | as the separator. Since Score is always the last item in each line, we use [-1] to grab it.
  • .strip() removes any extra spaces around the Score (e.g., if the line has Name | Email | 1000 , it cleans it to 1000).
  • Converting to int ensures we sort numerically (not lexicographically—so 100000 comes before 99999, which wouldn’t happen with string sorting).
Command-Line Solution (Unix/macOS)

If you’re comfortable with terminal commands, you can use a combination of awk, sort, and cut to sort the file in one line:

awk -F'|' '{gsub(/^ +| +$/,"",$3); print $3, $0}' your_input.txt | sort -nr | cut -d' ' -f2- > sorted_scores.txt

Breakdown of the command:

  1. awk -F'|': Splits each line using | as the delimiter.
  2. gsub(/^ +| +$/,"",$3): Cleans up any leading/trailing spaces from the Score field (third field, $3).
  3. print $3, $0: Prints the cleaned Score followed by the entire original line—this gives sort a clear numeric key to sort on.
  4. sort -nr: Sorts the output numerically (-n) in reverse (-r, highest to lowest) order.
  5. cut -d' ' -f2-: Removes the leading Score we added earlier, leaving only the original line structure.
  6. > sorted_scores.txt: Saves the final sorted output to a new file.

内容的提问来源于stack exchange,提问作者Andrew Wang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:37:15