파일 이름 세트에서 n번째 문자를 제거하는 방법은 무엇입니까?

파일 이름 세트에서 n번째 문자를 제거하는 방법은 무엇입니까?

안녕하세요, 저는 배치 파일 이름 바꾸기를 위한 bash 솔루션을 찾고 있습니다. 저속 촬영 영상으로 가져오는 디지털 카메라의 파일이 있습니다.

1000개의 이미지 JPG 파일 이름이 바뀔 때마다 다음과 같이 점프합니다.

./P1020998.JPG
./P1020999.JPG
./P1030001.JPG
./P1030002.JPG

After Effects로 가져올 때 이미지 개수가 연속적으로 표시되도록 다섯 번째 위치에서 "0"을 제거할 수 있는 재사용 가능한 셸 명령을 해킹하려고 합니다.

파일 이름 집합에서 n번째 문자를 제거하는 가장 빠르고 쉬운 방법을 아는 사람이 있습니까? 나는 항상 해당 디렉토리에 있는 일련의 이미지 외에는 다른 파일이 없는 디렉토리에 이미지를 그룹화합니다.

검색해 본 결과 지금까지의 해결 방법은 파일 이름에서 "0" 문자를 모두 제거하는 것 같았습니다. 이는 제가 특별히 원하는 것이 아닙니다.오직다섯 번째 문자를 제거하는 것이 내가 원하는 결과입니다. 시간을 내어 이 질문에 답변해 주셔서 감사합니다.

답변1

사용 중인 기능과 관련된 매뉴얼 페이지를 인용하는 것이 좋습니다. 다음 EXPANSION섹션 에서 man bash:

${parameter:offset:length}
       Substring  Expansion.  Expands to up to length characters of the value of parameter starting at the character specified by offset.  If parameter is @, an 
       indexed array subscripted by @ or *, or an associative array name, the results differ as described below.  If length is omitted, expands to the substring
       of  the value of parameter starting at the character specified by offset and extending to the end of the value.  length and offset are arithmetic expres‐
       sions (see ARITHMETIC EVALUATION below).

       If offset evaluates to a number less than zero, the value is used as an offset in characters from the end of the value of parameter.  If length evaluates
       to  a  number less than zero, it is interpreted as an offset in characters from the end of the value of parameter rather than a number of characters, and
       the expansion is the characters between offset and that result.  Note that a negative offset must be separated from the colon by at least  one  space  to 
       avoid being confused with the :- expansion.

내부적으로 산술 연산을 수행할 수 있으므로 ${}다음과 같이 코드를 매개변수화할 수 있습니다.

#!/bin/bash
position=5

for f in *JPG; do
   mv -- "$f" "${f:0:$position-1}${f:$position}"
done

exit

여기에 빠르고 더러운 해결책이 있습니다. 파일 이름의 길이나 기타 사항을 확인하지 않지만 이와 같은 해커에게는 괜찮을 것입니다.

답변2

rename(Perl 이름 바꾸기 또는 )을 사용합니다 prename.

rename -nv 's/^(.{4})0/$1/' ./*.jpg

우리는 다음을 대체합니다:

  • ^문자열의 시작을 어설션
  • (.{4})첫 번째 캡처링 그룹이고, 역방향 참조 $1점은 .모든 문자(ewline 제외 \n)와 일치하며 {4}이전 토큰과 정확히 4번 일치합니다.
  • 0문자 0과 일치합니다.

위 캡처 그룹의 내용만 사용하면 결과는 5번째 문자 위치에서 0자를 제거하는 것입니다(항상 0번째 문자와 일치하는 대신 5번째 위치 (ewline 제외)에서 $1임의의 문자를 제거하여 0을 대체할 수 있습니다 )..\n

regexper.com에서 생성됨

답변3

그것은 중요하지 않습니다! 쉘 스크립트 솔루션을 알아보세요. 같은 문제가 있어서 여기에 오시는 분들을 위해 제가 사용하는 쉘 코드는 다음과 같습니다.

cd DIRECTORYPATH         ## Navigate to directory with images

for f in *; do           ## Begin for loop with each file in directory
    x="${f::4}"          ## Set x as first 4 characters
    y="${f:5}"           ## Set y as all characters past position 5
    mv -- "$f" "$x$y"    ## Use mv command to rename each file as string x+y
done

답변4

또 다른 방법은sed

#!/bin/bash

cd $DIRECTORYPATH 

for f in *.JPG 
do
    mv $f $(echo $f | sed -e 's/\(^P[0-9]\{3\}\)0\([0-9]*\.JPG\)/\1\2/')
done

~

관련 정보