2

I have files with name of the form "NAME-xxxxxx.tedx" and I want to remove the "-xxxxxx" part. The x are all digits. The regex "\-[0-9]{1,6}" matches the substring, but I have no idea how to remove it from the filename.

Any idea how I can do that in the shell?

3 Answers 3

5

If you have the perl version of the rename command installed, you could try:

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

Demo:

[me@home]$ ls
hello-123.tedx  world-23456.tedx
[me@home]$ rename 's/-[0-9]+//' *.tedx
[me@home]$ ls
hello.tedx  world.tedx

This command is smart enough to not rename files if it means overwriting an existing file:

[me@home]$ ls
hello-123.tedx  world-123.tedx  world-23456.tedx
[me@home]$ rename 's/-[0-9]+//' *.tedx
world-23456.tedx not renamed: world.tedx already exists
[me@home]$ ls
hello.tedx  world-23456.tedx  world.tedx
Sign up to request clarification or add additional context in comments.

Comments

3
echo NAME-12345.tedx | sed "s/-[0-9]*//g"

will give NAME.tedx. So you can use a loop and move the files using mv command:

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

Comments

1

If you want to use just the shell

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.