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

如何使用PowerShell删除并替换文本文件指定两行间的内容

PowerShell替换指定标记行之间内容的实现

以下是直接可用的PowerShell脚本,实现删除elementLIST_PROPERTY与ElementFinList_Property之间的所有内容并替换为指定文本:

# 配置参数
$filePath = "你需要处理的文件路径"
$startTag = "elementLIST_PROPERTY"
$endTag = "ElementFinList_Property"
$replacementText = @"
    Camera
    Objectif
    Zoom
"@

# 读取文件内容到行数组
$allLines = Get-Content -Path $filePath

# 定位标记行的位置
$startPos = $allLines.IndexOf($startTag)
$endPos = $allLines.IndexOf($endTag)

# 校验标记有效性
if ($startPos -eq -1 -or $endPos -eq -1 -or $startPos -ge $endPos) {
    Write-Host "错误:未找到有效标记对或标记顺序异常"
    exit 1
}

# 构建新的内容行集合
$updatedLines = @(
    $allLines[0..$startPos],  # 起始标记之前的内容
    $replacementText -split "`n",  # 替换的新内容(拆分为单独行)
    $allLines[$endPos..($allLines.Count - 1)]  # 结束标记及之后的内容
)

# 将新内容写入文件
$updatedLines | Set-Content -Path $filePath -Encoding UTF8

关键说明

  • 替换$filePath为你的目标文件实际路径
  • $replacementText用Here-String格式保留换行和缩进,直接修改成你需要的内容即可
  • 脚本会先校验两个标记是否存在且起始标记在结束标记之前,避免误操作
  • 写入文件时指定-Encoding UTF8可以防止中文或特殊字符乱码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 04:45:29