
У меня есть 12 папок, каждая из которых содержит две подпапки: "Images" и "Json". Теперь каждая папка "Images" содержит 10 файлов изображений с именами от 1.png до 10.png, а каждая папка "Json" содержит 10 файлов с именами от 1.json до 10.json.
Итак, в общей сложности у меня 120 изображений и 120 файлов json. Я хочу рандомизировать их и переименовать в одну папку для изображений и одну папку для файлов json, так что у меня будут 1.png по 120.png в одной папке (в порядке рандомизации) и то же самое для файлов json.
Каждый файл json связан с файлом изображения, поэтому переименование 1.png и 1.json должно производиться на одно и то же имя.
Я пробовал переименовывать следующим образом, но поскольку я не силен в написании скриптов, я не знаю, как выполнить в точности вышеуказанное требование:
setlocal enabledelayedexpansion
set /a count=0
for /f "tokens=*" %%a in ('dir /b /od *.png') do (
ren %%a ArbitraryString!count!.png
set /a count+=1
)
и это
$i=1
Get-ChildItem | ForEach {
Rename-Item $_ -NewName ("filename" + $i + ".jpg")
$i++
}
Я был бы признателен за помощь. Спасибо.
решение1
Вы можете попробовать следующую команду:
'\Main\folder\' | ForEach-Object{$($_ + "\*.png"), $($_ + "\*.json")} | Get-ChildItem -Recurse | foreach { If ( $_.extension -ne $prevExt ) { $i=1 } Rename-Item $_.FullName -NewName ('{0}' -f $i++ +$_.extension); $prevExt = $_.extension; }
Note:
The files will be renamed in the source folder. It would be interesting to make a backup before running the above command.
Комментарии к команде:
'\Main\folder\' - is the path where the folder with all your files is.
The symbol | - it's called a pipeline, it's a concatenation command to join several functions in one line.
ForEach-Object - you are defining which file extensions you will want to change the names of.
Get-ChildItem -Recurse - will search for all files in folders and subfolders.
foreach - will execute the command to rename the files until the last one found.
{ If ( $_.extension -ne $prevExt ) { $i=1 } - will compare the current file extension, with the extension that was read previously,
the { $i=1 } is resetting the value of the counter which will be the sequential name of the file
when the extension changes.
Eg: 1.png, 2.png, 3.png... 1.json, 2.json, 3.json... that is, when the extension changes, the
counter starts a new sequence.
Rename-Item $_.FullName -NewName ('{0}' -f $i++ +$_.extension) - Rename-Item - is the command that will do the renaming of the files
$_.FullName - is the full name of the file
-NewName - is what name the file will be changed to, inside the parentheses are the parameters
of the new file name:
'{0}' - will be a file with numeric name
-f $i++ - which will be added 1 to 1
+$_.extension - keeping the original extension
$prevExt = $_.extension - very important item:
this is where the extension of the file being seen is updated with the extension read, so that the command
Rename-Item can know when the file extension has changed and start the next name with numering starting from 1.
Чтобы переименовать и скопировать все файлы в другую папку:
$fileRenamed = "C:\MyRenamedPngJsonFolder\"
foreach ($e in $("png","json")) {ls 'C:\MyOriginalPngJsonFolder' -r -filt *.$e | % {$i=1} { copy $_.FullName $("$fileRenamed"+$i+"."+$e) -Recurse; $i++}}
Файлы будут переименованы в выходной папке следующим образом:
1.json 1.png, 2.json 2.png, 3.json 3.png, 4.json 4.png, 5.json 5.png...
Примечание: Вы можете создать папку переименованных файлов в любом месте на вашем компьютере. Файлы в исходной папке не будут переименованы.
Я провел несколько тестов с помощью указанной выше команды и понял, что когда в выходной папке уже есть файлы, они перезаписываются новыми файлами и в конечном итоге теряются.
Я сделал более полный скрипт и в соответствии с вашими потребностями. Скрипт проверяет, есть ли файлы json и png во входной папке, проверяет, существует ли уже выходная папка, и если ее нет, он автоматически создает папку. Если папка уже существует, он возьмет последний существующий последовательный номер в папке и продолжит переименование с этого последнего номера, чтобы файлы не перекрывались.
Примечание:
С помощью этого скрипта вы можете поместить в папку другие расширения файлов, и он будет конвертировать только файлы png и json.
Этот скрипт создаст папку output_renamed_files_png_json с двумя подпапками для переименованных файлов. Например, output_renamed_files_png_json\JSON PNG.
Переименованные файлы будут скопированы в папку в соответствии с их расширением.
Например: output_renamed_files_png_json\JSON 1.json, 2.json, 3.json... output_renamed_files_png_json\PNG 1.png, 2.png, 3.png...
1.json 1.png, 2.json 2.png... ссылаются друг на друга, как вы сообщили в этом сообщении.
см. сценарий ниже:
$p=$j=0
$countyp = (ls 'path\original_files\*' -Recurse -Include *.json, *.png | Measure-Object ).Count; # Checks that there are json and png files in the input folder before starting the process
$files=Get-ChildItem -Recurse 'path\original_files\*' -Include *.json, *.png | Where {! $_.PSIsContainer } | # and select files if they exist.
% { { $_.extension }
If ($countyp -ne 0)
{
If ($_.extension -eq ".png") # Counts the amount of JSON and PNG files.
{
$p++
}
If ($_.extension -eq ".json")
{
$j++
}
}
}
If ($countyp -eq 0)
{
Write-Host "No PNG and JSON files found to be renamed!... type exit to finish and check for these files in the input folder." -foregroundcolor Red
Exit
}
If ($p -ne $j) # If the number of files are not the same, it shows a message informing you which file
{ # extension is missing and its amount.
If ($p -gt $j)
{
$tj=($p-$j)
Write-Host "$tj JSON file(s) is missing from input folder!... type exit to finish and check input folder." -foregroundcolor Red # Missing JSON extension message
}else {
$tp=($j-$p)
Write-Host "$tp PNG file(s) is missing from input folder!... type exit to finish and check input folder." -foregroundcolor Red # Missing PNG extension message
}
}else {
$Folder = 'path\Renamed_Files_png_json' # checks if the output folder already exists. If it doesn't exist, it will create it.
if ( -not (Test-Path -Path "$Folder") )
{
$null = (new-item -type directory -path 'path\Renamed_Files_png_json', 'path\Renamed_Files_png_json\JSON', 'path\Renamed_Files_png_json\PNG' -Force)
}
$pathRenamed = 'path\Renamed_Files_png_json\' # Associates the output folder path to the variable.
$count = ( Get-ChildItem -Recurse -File "$pathRenamed" | Measure-Object ).Count
If ( $count -eq 0) # If the folder was just created, the json and png file numbering starts from 1.
{
$ip=$ij=1
}
else { # If the folder already exists, the files in the folders will be counted for the number
$ip=$ij=($count/2)+1 # starting from the last number of the existing file. As you informed that the files
} # are always matched ( 1.json 1.png, 2.json 2.png), the total value is divided by 2.
foreach ($e in $("png","json")) {
ls 'path\original_files\' -r -filt *.$e | % { # Check the extension of files to copy them to the corresponding folder.
If ( $_.extension -eq ".json" )
{
copy $_.FullName $("$pathRenamed"+$e+"\"+$ij+"."+$e) -Recurse -Force; $ij++
}
else {
copy $_.FullName $("$pathRenamed"+$e+"\"+$ip+"."+$e) -Recurse -Force; $ip++
}
}
}
Write-Host "The files have been renamed... type exit to finish!" -foregroundcolor Green
}
If you still haven't found a solution for your post, test it with the script!