Programming

폴더의 파일 이름을 순차 번호로 바꾸기

procodes 2020. 5. 6. 22:23
반응형

폴더의 파일 이름을 순차 번호로 바꾸기


디렉토리의 파일 이름을 순차적 번호로 바꾸고 싶습니다. 파일 생성 날짜를 기준으로합니다.

예를 들어, sadf.jpg0001.jpg, wrjr3.jpg0002.jpg등등, 파일의 총 금액 (필요하지 않은 경우 추가 제로에 대한 필요)에 따라 선행 0의 수.


루프 letprintf패딩에 사용하십시오.

a=1
for i in *.jpg; do
  new=$(printf "%04d.jpg" "$a") #04 pad to length of 4
  mv -i -- "$i" "$new"
  let a=a+1
done

-i플래그를 사용하면 기존 파일을 자동으로 덮어 쓰지 않습니다.


한 줄의 아름다움 :

ls -v | cat -n | while read n f; do mv -n "$f" "$n.ext"; done 

당신은 변경할 수 .ext.png, .jpg


나는 단순성에 대한 gauteh의 솔루션을 좋아하지만 중요한 단점이 있습니다. 수천 개의 파일에서 실행하면 "인수 목록이 너무 깁니다"라는 메시지가 표시되고 ( 더 자세한 내용은이 스크립트에서) 스크립트가 느려질 수 있습니다. 필자의 경우 약 36.000 파일에서 실행하면 스크립트가 약 이동했습니다. 초당 1 개의 아이템! 왜 이런 일이 발생하는지 잘 모르겠지만 동료로부터 얻은 규칙은 " find당신의 친구" 였습니다.

find -name '*.jpg' | # find jpegs
gawk 'BEGIN{ a=1 }{ printf "mv %s %04d.jpg\n", $0, a++ }' | # build mv command
bash # run that command

아이템을 세고 명령을 빌드하기 위해 gawk 가 사용되었습니다. 그러나 주요 차이점에 유의하십시오. 기본적 find으로 현재 디렉토리 및 해당 서브 디렉토리에서 파일을 검색하므로 필요한 경우 현재 디렉토리에서만 검색을 제한 man find하십시오 (방법을 보려면 사용 하십시오).


OSX에서 Pero 솔루션을 사용하려면 약간의 수정이 필요했습니다. 나는 사용했다 :

find . -name '*.jpg' \
| awk 'BEGIN{ a=0 }{ printf "mv \"%s\" %04d.jpg\n", $0, a++ }' \
| bash

참고 : 백 슬래시는 줄 연속을 위해 있습니다.

2015 년 7 월 20 일 수정 : 공백이있는 파일 이름을 지원하기 위해 명령 \"%s\"인수 를 인용하기 위해 @klaustopher의 피드백을 통합했습니다 mv.


원래 확장명을 유지하고 선행 0을 추가하며 OSX에서도 작동하는 매우 간단한 bash 하나의 라이너

num=0; for i in *; do mv "$i" "$(printf '%04d' $num).${i#*.}"; ((num++)); done

http://ubuntuforums.org/showthread.php?t=1355021의 단순화 된 버전


"이름 바꾸기"명령으로

rename -N 0001 -X 's/.*/$N/' *.jpg

또는

rename -N 0001 's/.*/$N.jpg/' *.jpg

모든 상황에서 작동하려면 이름에 공백이있는 파일에 \ "를 넣으십시오.

find . -name '*.jpg' | gawk 'BEGIN{ a=1 }{ printf "mv \"%s\" %04d.jpg\n", $0, a++ }' | bash

rename지원하지 않는 경우 -N다음과 같이 할 수 있습니다.

ls -1 -c | xargs rename -n 's/.*/our $i; sprintf("%04d.jpg", $i++)/e'

편집 주어진 숫자로 시작하려면 아래의 (어떤 못생긴 것처럼 보이는) 코드를 사용하고 123을 원하는 숫자로 바꾸십시오.

ls -1 -c | xargs rename -n 's/.*/our $i; if(!$i) { $i=123; } sprintf("%04d.jpg", $i++)/e'

생성 시간순으로 파일을 나열한 다음 (가장 먼저 -r정렬하려면 ls에 추가 )이 파일 목록을 보내 이름을 바꿉니다. 이름 바꾸기는 정규식에서 perl 코드를 사용하여 카운터를 형식화하고 증가시킵니다.

그러나 EXIF ​​정보가 포함 된 JPEG 이미지를 다루는 경우 권장합니다. exiftool

이것은에서입니다 exiftool 문서 "이름 바꾸기 예"에서,

   exiftool '-FileName<CreateDate' -d %Y%m%d_%H%M%S%%-c.%%e dir

   Rename all images in "dir" according to the "CreateDate" date and time, adding a copy number with leading '-' if the file already exists ("%-c"), and
   preserving the original file extension (%e).  Note the extra '%' necessary to escape the filename codes (%c and %e) in the date format string.

OSX 에서 Homebrew의 이름 바꾸기 스크립트를 설치하십시오.

brew install rename

그러면 정말 말도 안되게 쉽게 할 수 있습니다.

rename -e 's/.*/$N.jpg/' *.jpg

또는 멋진 접두사를 추가하려면 다음을 수행하십시오.

rename -e 's/.*/photo-$N.jpg/' *.jpg

ls를 사용할 수도 있습니다

ls *.JPG| awk 'BEGIN{ a=0 }{ printf "mv %s gopro_%04d.jpg\n", $0, a++ }' | bash

I had a similar issue and wrote a shell script for that reason. I've decided to post it regardless that many good answers were already posted because I think it can be helpful for someone. Feel free to improve it!

numerate

@Gnutt The behavior you want can be achieved by typing the following:

./numerate.sh -d <path to directory> -o modtime -L 4 -b <startnumber> -r

If the option -r is left out the reaming will be only simulated (Should be helpful for testing).

The otion L describes the length of the target number (which will be filled with leading zeros) it is also possible to add a prefix/suffix with the options -p <prefix> -s <suffix>.

In case somebody wants the files to be sorted numerically before they get numbered, just remove the -o modtime option.


a=1

for i in *.jpg; do
 mv -- "$i" "$a.jpg"
 a=`expr $a + 1`
done

Let us assume we have these files in a directory, listed in order of creation, the first being the oldest:

a.jpg
b.JPG
c.jpeg
d.tar.gz
e

then ls -1cr outputs exactly the list above. You can then use rename:

ls -1cr | xargs rename -n 's/^[^\.]*(\..*)?$/our $i; sprintf("%03d$1", $i++)/e'

which outputs

rename(a.jpg, 000.jpg)
rename(b.JPG, 001.JPG)
rename(c.jpeg, 002.jpeg)
rename(d.tar.gz, 003.tar.gz)
Use of uninitialized value $1 in concatenation (.) or string at (eval 4) line 1.
rename(e, 004)

The warning ”use of uninitialized value […]” is displayed for files without an extension; you can ignore it.

Remove -n from the rename command to actually apply the renaming.

This answer is inspired by Luke’s answer of April 2014. It ignores Gnutt’s requirement of setting the number of leading zeroes depending on the total amount of files.


Again using Pero's solution with little modifying, because find will be traversing the directory tree in the order items are stored within the directory entries. This will (mostly) be consistent from run to run, on the same machine and will essentially be "file/directory creation order" if there have been no deletes.

However, in some case you need to get some logical order, say, by name, which is used in this example.

find -name '*.jpg' | sort -n | # find jpegs
gawk 'BEGIN{ a=1 }{ printf "mv %s %04d.jpg\n", $0, a++ }' | # build mv command
bash # run that command 

ls -1tr | rename -vn 's/.*/our $i;if(!$i){$i=1;} sprintf("%04d.jpg", $i++)/e'

rename -vn - remove n for off test mode

{$i=1;} - control start number

"%04d.jpg" - control count zero 04 and set output extension .jpg


To me this combination of answers worked perfectly:

ls -v | gawk 'BEGIN{ a=1 }{ printf "mv %s %04d.jpg\n", $0, a++ }' | bash
  • ls -v helps with ordering 1 10 9 in correct: 1 9 10 order, avoiding filename extension problems with jpg JPG jpeg
  • gawk 'BEGIN{ a=1 }{ printf "mv %s %04d.jpg\n", $0, a++ }' renumbers with 4 characters and leading zeros. By avoiding mv I do not accidentally try to overwrite anything that is there already by accidentally having the same number.
  • bash executes

Be aware of what @xhienne said, piping unknown content to bash is a security risk. But this was not the case for me as I was using my scanned photos.


The majority of the other solutions will overwrite existing files already named as a number. This is particularly a problem if running the script, adding more files, and then running the script again.

This script renames existing numerical files first:

#!/usr/bin/perl

use strict;
use warnings;

use File::Temp qw/tempfile/;

my $dir = $ARGV[0]
    or die "Please specify directory as first argument";

opendir(my $dh, $dir) or die "can't opendir $dir: $!";

# First rename any files that are already numeric
while (my @files = grep { /^[0-9]+(\..*)?$/ } readdir($dh))
{
    for my $old (@files) {
        my $ext = $old =~ /(\.[^.]+)$/ ? $1 : '';
        my ($fh, $new) = tempfile(DIR => $dir, SUFFIX => $ext);
        close $fh;
        rename "$dir/$old", $new;
    }
}

rewinddir $dh;
my $i;
while (my $file = readdir($dh))
{
    next if $file =~ /\A\.\.?\z/;
    my $ext = $file =~ /(\.[^.]+)$/ ? $1 : '';
    rename "$dir/$file", sprintf("%s/%04d%s", $dir, ++$i, $ext); 
}

Sorted by time, limited to jpg, leading zeroes and a basename (in case you likely want one):

ls -t *.jpg | cat -n |                                           \
while read n f; do mv "$f" "$(printf thumb_%04d.jpg $n)"; done

(all on one line, without the \)


This oneliner lists all files in the current directory, sorts by creation timestamp in reverse order (means the oldest file is at the beginning) and renames automatically with trailing zeros as required by the amount of files. The file extension will be preserved.

I usually have only one folder since years for mobile phone pictures and movies. Applying this command, my pictures and movies are ready then for a slideshow in the correct order on the tv or archiving as well.

Be aware that if you have file name collisions, you are losing files. So first rename to something odd like temp001.jpg and then execute to your final file name.

DIGITS=$(ls | wc -l | xargs | wc -c | xargs); ls -tcr | cat -n | while read n f; do mv "$f" "$(printf "%0${DIGITS}d" $n).${f##*.}"; done

Follow command rename all files to sequence and also lowercase extension:

rename --counter-format 000001 --lower-case --keep-extension --expr='$_ = "$N" if @EXT' *

This script will sort the files by creation date on Mac OS bash. I use it to mass rename videos. Just change the extension and the first part of the name.

ls -trU *.mp4| awk 'BEGIN{ a=0 }{ printf "mv %s lecture_%03d.mp4\n", $0, a++ }' | bash

Here a another solution with "rename" command:

find -name 'access.log.*.gz' | sort -Vr | rename 's/(\d+)/$1+1/ge'

If you are using image Annotator for labelling the images .

$ make qt5py3

$ python3 labelImg.py


Pero's answer got me here :)

I wanted to rename files relative to time as the image viewers did not display images in time order.

ls -tr *.jpg | # list jpegs relative to time
gawk 'BEGIN{ a=1 }{ printf "mv %s %04d.jpg\n", $0, a++ }' | # build mv command
bash # run that command

To renumber 6000, files in one folder you could use the 'Rename' option of the ACDsee program.

For defining a prefix use this format: ####"*"

Then set the start number and press Rename and the program will rename all 6000 files with sequential numbers.

참고URL : https://stackoverflow.com/questions/3211595/renaming-files-in-a-folder-to-sequential-numbers

반응형