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

如何用AppleScript格式化.txt列表:移除连字符及后续内容

AppleScript 处理文本文件移除“-”及后续内容

你的现有脚本只是判断了文件路径里有没有“-”,完全没涉及文件内容的读取、处理和写入,肯定无法运行。要实现需求,必须读取原文件内容、处理每行文本,并且需要定义输出文件路径(建议输出到新文件,避免覆盖原数据)。

下面是可以实现需求的完整脚本:

-- 定义输入文件路径
set inputFilePath to "/Users/home/Desktop/list.txt"
-- 定义输出文件路径(在原文件名后加_processed区分,避免覆盖原文件)
set outputFilePath to "/Users/home/Desktop/list_processed.txt"

-- 读取输入文件的UTF-8编码内容
set fileContents to read file inputFilePath as «class utf8»
-- 按换行符把内容分割成每行的列表
set lineList to paragraphs of fileContents

-- 初始化存储处理后内容的列表
set processedLines to {}

-- 遍历每一行做处理
repeat with aLine in lineList
    -- 找到该行中第一个“-”的位置
    set dashIndex to offset of "-" in aLine
    if dashIndex > 0 then
        -- 截取“-”之前的部分
        set processedLine to text 1 through (dashIndex - 1) of aLine
    else
        -- 没有“-”的行直接保留原内容
        set processedLine to aLine
    end if
    -- 把处理后的行添加到列表
    set end of processedLines to processedLine
end repeat

-- 将处理后的行列表合并成带换行符的文本
set processedContents to (processedLines as text) & linefeed

-- 写入输出文件
set outputFile to open for access file outputFilePath with write permission
write processedContents to outputFile starting at eof
close access outputFile

-- 弹出提示告知处理完成
display dialog "处理完成,结果已保存到: " & outputFilePath

关键说明

  • 明确输入/输出路径:避免误删原文件,同时清晰指定结果存储位置
  • 逐行处理逻辑:针对每行单独判断是否包含“-”,精准截取需要的内容
  • 完整读写流程:从读取原文件到写入处理后内容,覆盖了需求的全流程

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 05:30:59