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

PowerShell中截取字符串数组内第一个短横线前的内容

提取字符串中第一个短横线前的内容

给定待处理的字符串数组:

Cola-12-0-15-300-122
Pepsi-123-34-543
7_Up-rrr-12-2342-2
Fanta_Mineral-1212-fgdfg-33

目标是提取每个字符串里第一个短横线(-)之前的内容,同时将7_Up转为7_up,最终得到如下结果:

Cola
Pepsi
7_up
Fanta_Mineral

方法一:Python 实现

通过字符串分割和简单替换处理即可完成需求:

# 原始字符串列表
raw_strings = [
    "Cola-12-0-15-300-122",
    "Pepsi-123-34-543",
    "7_Up-rrr-12-2342-2",
    "Fanta_Mineral-1212-fgdfg-33"
]

processed = []
for s in raw_strings:
    # 按短横线分割,取第一个片段
    first_part = s.split('-')[0]
    # 单独处理7_Up的大小写问题
    if first_part == "7_Up":
        first_part = "7_up"
    processed.append(first_part)

# 打印结果
for item in processed:
    print(item)

方法二:Shell 命令实现

如果是处理文件中的内容,可结合awk和sed快速完成:

# 假设内容保存在input.txt中
awk -F '-' '{print $1}' input.txt | sed 's/7_Up/7_up/'

运行上述任一方案,都能得到预期的输出结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 07:10:29