[英]Search string and delete everythig else and paste to new file with Powershell
In main directory "Movies" I have multiple directories with "Movie Name" and each directory contain "movie_name.nfo" file.在主目录“电影”中,我有多个带有“电影名称”的目录,每个目录都包含“电影名称.nfo”文件。
Movies
|- Avatar
- Avatar.nfo
|- Ad Astra
- Ad Astra.nfo
In those "movie_name.nfo" files I have multiple links and each link is stored in separated line:在那些“movie_name.nfo”文件中,我有多个链接,每个链接都存储在单独的行中:
http://www.imdb.com/title/tt8134742/
https://www.themoviedb.org/movie/489064/
http://www.csfd.cz/film/603376
What I want is:我想要的是:
If "movie_name.nfo" file contain string "themoviedb", then everything else is deleted in that file except that line which contain searched string.如果“movie_name.nfo”文件包含字符串“themoviedb”,那么除了包含搜索字符串的那一行之外,该文件中的所有其他内容都将被删除。 Every lines which was deleted (not contain searched string) are copied to new file with name "movie.nfo" in same folder as is "movie_name.nfo" file.被删除的每一行(不包含搜索字符串)都被复制到与“movie_name.nfo”文件相同的文件夹中名为“movie.nfo”的新文件中。
I tried several options, but without success, this is what I have now,我尝试了几种选择,但没有成功,这就是我现在所拥有的,
Get-Content -Path "./*" -Filter *.nfo -Recurse | Where {$_ -notmatch "themoviedb"} | Set-Content "movie.nfo"
Thank you.谢谢你。
Assuming the movie info files always have the same basename like their folder you can use a loop to假设电影信息文件始终具有与其文件夹相同的基本名称,您可以使用循环来
You could start with something like this:你可以从这样的事情开始:
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
}
}
I'd recommend to read always the complete help for the cmdlets you use ... including the examples to learn how to use them.我建议您始终阅读您使用的 cmdlet 的完整帮助......包括学习如何使用它们的示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.