Powershell 或批处理 : find and replace characters

标签 powershell batch-file replace

我有十个文本文件(制表符分隔,20 万行)。我的意图是寻找字符 [, ], |并分别用 a、o、u 替换它们。任何提示如何使用 Windows 批处理脚本或 Powershell 执行此操作?

最佳答案

这应该会处理它,使用 Powershell。这可以通过直接 cmd.exe 来完成东西和一些内置的 Windows 可执行文件,但它会更丑陋,更难以理解。

它将读取某个文件,并在每一行中读取:

  • 替换 [a
  • 替换 ]o
  • 替换 |u

  • [ 起需要转义符, ] , 和 |都是powershell中的特殊字符,反引号`用于自动换行命令。
    $filename="textfile.txt"
    $outputfile="$filename" + ".out"
    
    Get-Content $filename | Foreach-object {
        $_ -replace '\[', 'a' `
           -replace '\]', 'o' `
           -replace '\|', 'u'
    } | Set-Content $outputfile
    

    如果要处理文件列表,可以设置一个数组来执行此操作,并遍历该数组。
    $filenames = @("/path/to/File1.txt", "file2.txt", "file3.txt")
    foreach ($file in $filenames) {
        $outfile = "$file" + ".out"
    
        Get-Content $file | Foreach-object {
            $_ -replace '\[', 'a' `
               -replace '\]', 'o' `
               -replace '\|', 'u'
        } | Set-Content $outfile
    }
    

    关于Powershell 或批处理 : find and replace characters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4126603/

    相关文章:

    powershell - 显示将要运行的命令

    Powershell - 自定义对象中的多个值

    xml - PowerShell 将 Get-Content 存储到变量中不返回任何数据

    batch-file - 如何在批处理文件中从 DOS 路径转换为文件方案 URI

    windows - 如果未复制任何文件,则在复制结束时生成错误

    python - 当满足条件时,使列行与另一列的匹配值相同

    c# - 从 DateTime 值中删除正斜杠、冒号和 AM/PM

    powershell - 在哈希表数组中搜索键的最简洁方法

    installation - 使用 nsis 安装程序创建批处理文件快捷方式的图标

    javascript - 将类似字符串的数组替换为带有字符替换的数组