Renaming text files based on the first word in the file in Powershell

最后都变了- 提交于 2021-01-29 09:32:32

问题


I found many similar examples but not this exact goal. I have a fairly large number of text files that all have a similar first word (clipxx) where xx is a different number in each file.

I want to rename each file using the first word in the file. Here is what I have tried using Powershell. I get an error that I cannot call a method on a null valued expression.

Get-ChildItem *.avs | ForEach-Object { Rename-Item = Get-Content ($line.Split(" "))[0] }

回答1:


I'd do this in three parts:

  1. Get the list of files you want to change.
  2. Create and map the new name for each file.
  3. Rename the files.

phase-1: get the list of files you want to change.

$files = Get-ChildItem *.avs

phase-2: map the file name to a new name

$file_map = @()
foreach ($file in $files) {
    $file_map += @{
        OldName = $file.Fullname
        NewName = "{0}.avs" -f $(Get-Content $file.Fullname| select -First 1)
    }
}

phase-3: make the name change

$file_map | % { Rename-Item -Path $_.OldName -NewName $_.NewName }

Changing things in a list that you're enumerating can be tricky. That's why I recommend breaking this up.

Here is me running this on my machine...

And, here is what was in my files...

Good Luck



来源:https://stackoverflow.com/questions/51029187/renaming-text-files-based-on-the-first-word-in-the-file-in-powershell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!