簡體   English   中英

使用 powershell 在目錄中的所有 the.log 文件中搜索字符串

[英]search a string in all the .log files in a directory using powershell

我想在包含字符串“scp 錯誤”的文件夾中讀取今天文件時間戳(即今天的日期 yyyymmdd)的所有 .log 文件。 如果條件滿足,則將不帶擴展名的 .log 文件的名稱移動到新的 .txt 文件“redrop_files.txt”

這是我到目前為止嘗試過的

Get-Item File*.log | ForEach-Object {
    $fil = $_.Name;
    
    foreach ($line in Get-Content $fil) {
        if ($line -eq "scp error") {
            $stat = "FAILED"
        }
    }

    if ($stat -eq "FAILED") {
        $errorfile = Get-ChildItem *.log | Rename-Item -NewName { $fil -replace '.log','' }
        Add-Content -Path .\redrop_files.txt "`n" $errorfile
    }
}

您有一個主要問題:您沒有將grep的結果存儲在任何地方,因此變量f未定義。

如果您只想要文件名,則不清楚為什么將-n與 grep 一起使用; -l似乎更有意義。

所以:

grep --include=\*.log -rlw '/path/' -e "scp error" |\
while read -r f; do
    echo "${f%%.*}"  
done > redrop_files.txt

嘗試以下,

path=.
while read file; do
  echo ${file%%:*} >> redrop_files.txt
done < <(grep --include=\*.log -rnw $path -e "scp error")

您的代碼有一些小錯誤,您可以使用一些改進,例如使用switch讀取文件。 最大的問題是您實際上是在重命名文件, Rename-Item實際上是在重命名文件。 您要做的是 append .BaseName屬性(不帶擴展名的文件名)到您的redrop_files.txt文件。

Get-Item File*.log | ForEach-Object {
    # if this file is not from Today
    if($_.CreationTime -lt [datetime]::Today) {
        # skip it
        return
    }

    $append = switch -Wildcard -File $_.FullName {
        # if the line contains "scp error"
        '*scp error*' {
            # output true
            $true
            # and break this loop, no need to keep checking
            break
        }
    }

    # if the result of the switch loop was true
    if ($append) {
        # append to redrop_files.txt the .BaseName of this file
        Add-Content -Value $_.BaseName -Path .\redrop_files.txt
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM