파일 이름을 다른 파일에서 다른 확장자를 가진 동일한 이름으로 바꿉니다.

파일 이름을 다른 파일에서 다른 확장자를 가진 동일한 이름으로 바꿉니다.

각 폴더에는 "Images"와 "Json"이라는 두 개의 하위 폴더가 포함된 12개의 폴더가 있습니다. 이제 각 "Images" 폴더에는 1.png에서 10.png까지 이름이 지정된 10개의 이미지 파일이 있고, 각 "Json" 폴더에는 1.json에서 10.json까지 이름이 지정된 10개의 파일이 있습니다.

그래서 총 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 폴더를 생성합니다. 예. 출력_이름이 바뀐_파일_png_json\JSON PNG.

이름이 바뀐 파일은 확장자에 따라 폴더에 복사됩니다.
예. 출력_변경된_파일_png_json\JSON 1.json, 2.json, 3.json... 출력_변경된_파일_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!

관련 정보