
Tengo 12 carpetas y cada una contiene dos subcarpetas: "Imágenes" y "Json". Ahora cada carpeta "Imágenes" tiene 10 archivos de imagen con nombres de 1.png a 10.png y cada carpeta "Json" tiene 10 archivos con nombres de 1.json a 10.json.
Entonces en total tengo 120 imágenes y 120 archivos json. Quiero aleatorizarlos y cambiarles el nombre en una carpeta para imágenes y una carpeta para archivos json, así que tendré 1.png a 120.png en una carpeta (para que sean aleatorios) y lo mismo para los archivos json.
Cada archivo json está conectado al archivo de imagen, por lo que el cambio de nombre de 1.png y 1.json debe ser el mismo.
Intenté cambiar el nombre de esta manera, pero como no soy bueno con las secuencias de comandos, no sé cómo realizar exactamente el requisito anterior:
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
)
y esto
$i=1
Get-ChildItem | ForEach {
Rename-Item $_ -NewName ("filename" + $i + ".jpg")
$i++
}
Agradecería algo de ayuda. Gracias.
Respuesta1
Puedes probar el siguiente comando:
'\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.
Comentarios del comando:
'\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.
Para cambiar el nombre y copiar todos los archivos juntos a otra carpeta:
$fileRenamed = "C:\MyRenamedPngJsonFolder\"
foreach ($e in $("png","json")) {ls 'C:\MyOriginalPngJsonFolder' -r -filt *.$e | % {$i=1} { copy $_.FullName $("$fileRenamed"+$i+"."+$e) -Recurse; $i++}}
Se cambiará el nombre de los archivos en la carpeta de salida de la siguiente manera:
1.json 1.png, 2.json 2.png, 3.json 3.png, 4.json 4.png, 5.json 5.png...
Nota: Puede crear la carpeta de archivos renombrados en cualquier lugar de su computadora. No se cambiará el nombre de los archivos de la carpeta de origen.
Hice algunas pruebas con el comando anterior y me di cuenta de que cuando ya hay archivos en la carpeta de salida, se sobrescriben con archivos nuevos y terminan perdiéndose.
Hice un guión más completo y acorde a tu necesidad. El script verifica si hay archivos json y png en la carpeta de entrada, verifica si la carpeta de salida ya existe y, si no es así, crea la carpeta automáticamente. Si la carpeta ya existe, tomará el último número secuencial existente en la carpeta y continuará cambiando el nombre a partir de este último número para que los archivos no se superpongan.
Nota:
Con este script puedes poner otras extensiones de archivo en la carpeta y solo convertirá archivos png y json.
Este script creará una carpeta output_renamed_files_png_json con dos subcarpetas para los archivos renombrados. p.ej. salida_renombrado_archivos_png_json\JSON PNG.
Los archivos renombrados se copiarán a la carpeta según su extensión.
p.ej. archivos_renombrados_png_json\JSON 1.json, 2.json, 3.json... archivos_renombrados_png_json\PNG 1.png, 2.png, 3.png...
1.json 1.png, 2.json 2.png... se refieren entre sí como usted informó en esta publicación.
ver guión a continuación:
$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!