2012-12-19 3 views
1

"NAME-xxxxxx.tedx"형식의 파일 이름이 있으며 "-xxxxxx"부분을 제거하고 싶습니다. x는 모두 숫자입니다. 정규 표현식 "\-[0-9]{1,6}"이 부분 문자열과 일치하지만 파일 이름에서 제거하는 방법을 알지 못합니다.파일 이름 부분 문자열 제거

쉘에서 어떻게 할 수 있습니까?

답변

4

, 당신은 시도 할 수 :

rename 's/-[0-9]+//' *.tedx 

데모 :

[[email protected]]$ ls 
hello-123.tedx world-23456.tedx 
[[email protected]]$ rename 's/-[0-9]+//' *.tedx 
[[email protected]]$ ls 
hello.tedx world.tedx 

이 명령을 기존 파일을 덮어 쓰는 경우 파일의 이름을 바꾸지 않아도됩니다.

[[email protected]]$ ls 
hello-123.tedx world-123.tedx world-23456.tedx 
[[email protected]]$ rename 's/-[0-9]+//' *.tedx 
world-23456.tedx not renamed: world.tedx already exists 
[[email protected]]$ ls 
hello.tedx world-23456.tedx world.tedx 
1
echo NAME-12345.tedx | sed "s/-[0-9]*//g" 

NAME.tedx이됩니다. 당신이 mv 명령을 사용하여 파일을 루프를 사용하여 이동할 수 있습니다 : 당신이 perl version of the rename command 설치 한 경우

for file in *.tedx; do 
    newfile=$(echo "$file" | sed "s/-[0-9]*//g") 
    mv "$file" $newfile 
done 
0

당신은 단지 셸을 사용하려면

shopt -s extglob 
for f in *-+([0-9]]).tedx; do 
    newname=${f%-*}.tedx # strip off the dash and all following chars 
    [[ -f $newname ]] || mv "$f" "$newname" 
done