簡體   English   中英

搜索字符串並刪除其他所有內容並使用 Powershell 粘貼到新文件

[英]Search string and delete everythig else and paste to new file with Powershell

在主目錄“電影”中,我有多個帶有“電影名稱”的目錄,每個目錄都包含“電影名稱.nfo”文件。

Movies
  |- Avatar
       - Avatar.nfo
  |- Ad Astra
       - Ad Astra.nfo

在那些“movie_name.nfo”文件中,我有多個鏈接,每個鏈接都存儲在單獨的行中:

http://www.imdb.com/title/tt8134742/
https://www.themoviedb.org/movie/489064/
http://www.csfd.cz/film/603376

我想要的是:

如果“movie_name.nfo”文件包含字符串“themoviedb”,那么除了包含搜索字符串的那一行之外,該文件中的所有其他內容都將被刪除。 被刪除的每一行(不包含搜索字符串)都被復制到與“movie_name.nfo”文件相同的文件夾中名為“movie.nfo”的新文件中。

我嘗試了幾種選擇,但沒有成功,這就是我現在所擁有的,

Get-Content -Path "./*" -Filter *.nfo -Recurse | Where {$_ -notmatch "themoviedb"} | Set-Content "movie.nfo"

謝謝你。

假設電影信息文件始終具有與其文件夾相同的基本名稱,您可以使用循環來

  1. 使用Join-Path “構造”目標文件名
  2. 檢查文件是否包含帶有Select-String的模式
  3. 如果有匹配項,則使用Select-Object刪除所有其他行
  4. 如果不使用Out-File創建一個包含模式的新文件

你可以從這樣的事情開始:

Get-ChildItem -Path .\movies -Directory |
ForEach-Object {
    $Pattern = 'themoviedb'
    $FileName = Join-Path -Path $_.FullName -ChildPath ($_.BaseName + '.nfo')
    $tempResult = Select-String -Path $FileName -Pattern $Pattern 
    if ($tempResult) {
        $Content = Get-Content -Path $FileName
        $Content | 
            Select-Object -Skip ($tempResult.LineNumber - 1) -First 1 |
                Set-Content -Path $FileName -Force
        $nfoFileName = Join-Path -Path $_.FullName -ChildPath 'movie.nfo'
        $newContent = $Content |
            Select-Object -First ($tempResult.LineNumber - 1) |
                Out-String
        $newContent += $Content |
            Select-Object -Skip ($tempResult.LineNumber) |
                Out-String
        $newContent |
            Out-File -FilePath $nfoFileName
    }
    else {
        $nfoFileName = Join-Path -Path $_.FullName -ChildPath 'movie.nfo'
        $Pattern | 
            Out-File -FilePath $nfoFileName
    }
}

我建議您始終閱讀您使用的 cmdlet 的完整幫助......包括學習如何使用它們的示例。

暫無
暫無

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

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