【问题标题】:Batch Script for filtering rows from textfile用于从文本文件中过滤行的批处理脚本
【发布时间】:2013-12-07 02:28:34
【问题描述】:

首先:我在 Windows 7 机器上;)。

我有一个包含几十个文件的文件夹。每个文件包含大约 240.000 行。但只需要其中一半的行。

我想做的是:有一个脚本在这些文件上运行,过滤掉包含字符串“abcd”的每一行,并将其保存在新目录中或仅保存在同一个文件中。

【问题讨论】:

  • 您想要批处理文件还是 Powershell 解决方案?
  • 好吧,我不介意老实说 :) 只要它有效 :)
  • 您希望将所有文件中的所有 'abcd' 行收集到一个文件中还是单独的文件中?

标签: powershell batch-file powershell-2.0


【解决方案1】:

我会尝试如下使用 Powershell:

$currentPath = "the path these files currently in"
$newPath     = "the path you want to put the new files"

$files = Get-ChildItem $currentPath

foreach ($item in $files) {
    Get-Content $item | Where-Object {$_ -notmatch 'abcd'} |Set-Content $newPath\$item
}

【讨论】:

    【解决方案2】:
    @echo off
        setlocal enableextensions 
    
        set "_where=c:\some\where\*.txt"
        set "_filter=abcd"
    
    rem find files which needs filter
    for /f "tokens=*" %%f in ('findstr /m "%_filter%" "%_where%"') do (
    
        rem generate a temporary file with the valid content
        findstr /v /c:"%_filter%" "%%~ff" > "%%~ff.tmp"
    
        rem rename original file to .old
        ren "%%~ff" *.old   > nul 
    
        rem rename temporary file as original file
        ren "%%~ff.tmp" "%%~nxf" > nul
    
    )
    rem if needed, delete *.old files
    

    【讨论】:

      【解决方案3】:

      你可以使用sed for Windows

      sed -i.bak "/abcd/!d" *.txt
      

      .txt文件中查找所有包含行的abcd,制作备份文件.bak并将检测到的行存储在原始文件中。

      【讨论】:

        【解决方案4】:
        @echo on
        For %%a in (*.txt) do (CALL:FILTER "%%a")
        echo/Done.&pause>nul&exit/b
        :FILTER
        type "%~1"|find "abcd" 1>nul 2>nul
        if %errorlevel% EQU 0 find /n "abcd" "%~1">"Found abcd in %~1.txt"
        

        如果他找到东西,命令 Find 返回错误级别 = 0

        【讨论】:

          【解决方案5】:

          如果文件那么大,我会这样:

          $Folder = 'C:\MyOldFiles'
          $NewFolder = 'C:\MyNewFiles'
          New-Item -ItemType Directory -Path $NewFolder -Force
          
          foreach ($file in Get-ChildItem $Folder)
           {
             Get-Content $file -ReadCount 1500 |
              foreach { $_ -notmatch 'abcd' } |
              Add-Content "$NewFolder\$($file.name)"
           }
          

          【讨论】:

            猜你喜欢
            • 2020-04-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-06-14
            • 1970-01-01
            • 1970-01-01
            • 2013-12-27
            • 1970-01-01
            相关资源
            最近更新 更多