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

如何用Bash按@后的字符串对文本行进行字母排序?

按@之后的字符串对多行邮箱排序

如果需要对多行邮箱字符串按@后的域名部分排序,下面提供两种实用方法:

方法1:使用Linux/macOS终端的sort命令

直接利用sort命令的字段排序功能,指定@作为分隔符,按第二部分(@后的内容)排序:

sort -t '@' -k 2

使用示例

假设你有如下输入内容:

alice@example.com
austin@microsoft.com
berto@example.com
charles@test.com
dorian@microsoft.com

将上述内容输入到终端后执行sort -t '@' -k 2,或者把内容保存为文件(比如emails.txt)后运行:

sort -t '@' -k 2 emails.txt

得到的输出就是:

alice@example.com
berto@example.com
austin@microsoft.com
dorian@microsoft.com
charles@test.com

参数说明:

  • -t '@':设置字段分隔符为@
  • -k 2:指定按第二个字段(即@之后的字符串)进行排序

方法2:使用Python脚本

如果需要跨平台(比如Windows)实现,或者需要更灵活的处理逻辑,可以用Python脚本:

import sys

# 读取输入的所有行,过滤空行
lines = [line.rstrip('\n') for line in sys.stdin if line.strip()]
# 按@分割后的第二部分作为排序依据
sorted_lines = sorted(lines, key=lambda email: email.split('@')[1])
# 输出排序后的结果
print('\n'.join(sorted_lines))

使用示例

  1. 将上述代码保存为sort_emails.py
  2. 若输入内容在文件emails.txt中,运行:
python sort_emails.py < emails.txt
  1. 也可以直接在终端输入内容,输入完成后按下Ctrl+D(Linux/macOS)或Ctrl+Z(Windows)结束输入,脚本会直接输出排序后的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 04:12:39