-2

I have multiple file in a folder with this format of name

01. file one-sdvanv-12lknl.srt
01. file one-sdvanv-12lknl.mp4
02. file two-afdsmakl-asdfafdaf.srt
02. file two-afdsmakl-asdfafdaf.mp4
03. file three-adfadaasd-asdfadfafad-adad1d1das.srt
03. file three-adfadaasd-asdfadfafad-adad1d1das.mp4

Now how to remove the string after - so the file name will looks like this

01. file one.srt
01. file one.mp4
02. file two.srt
02. file two.mp4
03. file three.srt
03. file three.mp4
Aditya
  • 139
  • 3
  • 7

3 Answers3

0
for file in *; do
    ext=.${file##*.}                #Gets file extension
    [ "$ext" = ".$file" ] && ext="" #If file had no extension, set it to empty string
    nostr=${file%%-*}               #Remove everything after -
    mv "$file" "$nostr$ext"
done
Quasímodo
  • 18,865
  • 4
  • 36
  • 73
-1

You could use bash parameter substitution like this:

for i in *; do
  # ${i%%-*} get everything before the first '-' (use ${i%-*} for the last '-')
  # ${i/.*} remove everything after the '.'
  # ${i##${i%.*}} remove everything except everything after the last '.'
  mv "${i}" "${i%%-*}${i##${i%.*}}"
done
noAnton
  • 361
-1

Using a loop in bash:

for name in *.mp4 *.srt; do
    mv -i -- "$name" "${name/-*./.}"
done

This renames each .mp4 file and .srt file by replacing the part of the name between the first dash and the last dot with a dot, by means of a variable substitution.

I chose to pick out the .mp4 and .srt files specifically, since these are the ones you show in the question.

Using a portable sh loop:

for name in *.mp4 *.srt; do
    mv -i -- "$name" "${name%%-*}.${name##*.}"
done

Here, ${name%%-*} will be the original name with everything after the first dash cut off, and ${name##*.} will be the filename suffix after the last dot in the filename.


Using the Perl rename utility:

$ tree
.
|-- 01. file one-sdvanv-12lknl.mp4
|-- 01. file one-sdvanv-12lknl.srt
|-- 02. file two-afdsmakl-asdfafdaf.mp4
|-- 02. file two-afdsmakl-asdfafdaf.srt
|-- 03. file three-adfadaasd-asdfadfafad-adad1d1das.mp4
`-- 03. file three-adfadaasd-asdfadfafad-adad1d1das.srt

0 directory, 6 files

$ rename 's/-.*\././' -- *.mp4 *.srt
$ tree
.
|-- 01. file one.mp4
|-- 01. file one.srt
|-- 02. file two.mp4
|-- 02. file two.srt
|-- 03. file three.mp4
`-- 03. file three.srt

0 directory, 6 files

The Perl expression s/-.*\././ is a substitution that will be applied to each given filename, renaming the file.

This substitution replaces the part of the filename from the first dash to the last dot with a dot.

You may want to add -n to the invocation of the rename utility to first see what would happen.

See also:

Kusalananda
  • 333,661