【问题标题】:script to convert all .txt file content to lowercase将所有 .txt 文件内容转换为小写的脚本
【发布时间】:2017-12-13 12:05:24
【问题描述】:

我有大约 700 个 .txt 文件分散在 300 个目录和子目录中。

我想分别打开它们,将里面的所有文本转换为小写,包括Unicode字符(例如Éé),然后保存并关闭它们。

您能否建议如何通过 PowerShell 完成?这是我自己的电脑,我有管理员权限。

我从以下开始:

Get-ChildItem C:\tmp -Recurse -File | ForEach-Object {}

但我不确定在 ForEach-Object {} 的括号之间放什么。

【问题讨论】:

    标签: windows powershell lowercase


    【解决方案1】:

    简单的脚本,符合您的要求:

    $path=".\test\*.txt"
    #With Default system encoding
    Get-ChildItem $path -Recurse | foreach{    
        (Get-Content $_.FullName).ToLower() | Out-File $_.FullName
    }
    
    #Or with specified encoding    
    Get-ChildItem $path -Recurse | foreach{    
    (Get-Content $_.FullName -Encoding Unicode).ToLower() | 
        Out-File $_.FullName -Encoding Unicode
    }
    #Test
    Get-ChildItem $path -Recurse | foreach{
        Write-Host "`n File ($_.FullName): `n" -ForegroundColor DarkGreen
        Get-Content $_.FullName    
    }
    

    【讨论】:

      【解决方案2】:

      你需要使用:

      # Reading the file content and converting it to lowercase and finally putting the content back to the file with the same filename.
      (Get-Content C:\path\file.txt -Raw).ToLower() | Out-File C:\path\file.txt -Force
      

      在foreach里面再把大小写改小。

      如果您想迭代相应文件夹中的所有文件,则可以使用另一个 foreach 来完成该工作。

      希望对你有帮助。

      【讨论】:

      • 我试过这个:Get-ChildItem C:\tmp -Recurse -File | ForEach-Object {(Get-Content $_ -Raw).ToLower() | Out-File $_ -Force} 但它返回错误:(
      • 这个有效:Get-ChildItem D:\test -Recurse -File | ForEach-Object {(Get-Content D:test\$_ -Raw).ToLower() | Out-File D:\test\$_ -Force} 但如何将其限制为仅 .txt 文件?
      • 非常简单。试试这个:Get-ChildItem D:\test -Recurse -File -Include *.txt | ForEach-Object {(Get-Content D:test\$_ -Raw).ToLower()} | Out-File D:\test\$_ -Force 使用 -Include *.txt 仅指定 txt 文件。
      • 接受答案将是可观的
      • 当然,我很乐意接受答案,但我收到以下错误消息:( Out-File : Could not find a part of the path 'D:\test\'。在line:1 char:113 + ... {(Get-Content D:test\$_ -Raw).ToLower()} | Out-File D:\test\$_ -Force + ~~~~~~~ ~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OpenError: (:) [Out-File], DirectoryNotFoundException + FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand
      猜你喜欢
      • 2016-05-25
      • 2019-11-02
      • 1970-01-01
      • 2018-08-26
      • 2022-01-04
      • 2011-08-06
      • 1970-01-01
      • 1970-01-01
      • 2012-08-02
      相关资源
      最近更新 更多