首页 > 解决方案 > 有没有办法可以批量删除 900ish 文件的部分文件名?

问题描述

需要一种方法来删除文件名的一部分。

尝试了一些基本记事本++的东西哈哈

https://i.imgur.com/SM8QbWq.jpg

图片主要显示我需要的东西!

例如

Sevenberry_island_paradise-SB-4131D1-4-S5090015(.jpg) 到 Sevenberry_island_paradise-SB-4131D1-4(.jpg)

商品代码在 SB- 之后,例如 4131D1-4,在此之后的所有内容我都不想要。

从所有这些文件中删除它的任何方法都将是一个巨大的巨大帮助!

谢谢!!

标签: windowsrenamenaming

解决方案


该问题不适合发布,您需要发布您尝试过的内容并就您自己的代码以及您遇到的任何错误消息或意外结果寻求帮助。话虽这么说,我看到了你的问题,想出一个解决方案似乎很有趣,所以我做到了。

此代码将查找指定目录中的所有文件(您也可以将-Recurse参数添加到该Get-ChildItem行以获取所有子目录中的文件)并将它们全部重命名,使用 RegEx 删除文件名的末尾。

在尝试之前复制您的文件。我已尽力创建一个适用于您所描绘的文件名的解决方案,但如果文件名与所描绘的非常不同,那么您可能会产生意想不到的结果。先做个备份。

# Specify the path in which all of your jpgs are stored
$path = 'C:\Path\To\Jpgs'
# Get all of the files we want to change, and only return files that have the .jpg extension
$jpgs = Get-ChildItem -Path "$path" <#-Recurse#> | Where-Object {$_.Extension -eq '.jpg'}
# Perform the same steps below on every file that we got above by using foreach
foreach ($jpg in $jpgs) {
    # Store the original file name in a variable for working on
    [string]$originalBaseName = "$($jpg.BaseName)"
    # Use RegEx to split the file name
    [string]$substringToReplace = ($originalBaseName -split '-[0-9]+-')[1]
    # Re-add the '-' to the string which you want to remove from the file name
    [string]$substringToReplace = '-' + $substringToReplace
    # Remove the portion of the file name you want gone
    [string]$newBaseName = $originalBaseName -replace "$substringToReplace",''
    # Rename the file with the new file name
    Rename-Item -Path "$($jpg.FullName)" -NewName "$newBaseName$($jpg.Extension)"
}

推荐阅读