1

I've got dozens of files such as:

title.mkv]-[72+167] - "" yEnc  637005001 (1+889)

I'd like to remove everything after ".mkv"

I tried looking up some regex that would help me, but I don't understand how to use them.

Could somebody help me?

telometto
  • 1,975

4 Answers4

3

Note on rename, prename etc. see:

In this answer the Perl variant is used, not the one form util-linux. As in not:

$ rename --version
rename from util-linux 2.31.1

but:

$ rename --version
/usr/bin/rename using File::Rename version 0.20

or similar.


With Perl rename:

rename 's/\.mkv.*/.mkv/s' ./*.mkv*

Use the -n option first to make sure it does what you want.

rename -n 's/\.mkv.*/.mkv/s' ./*.mkv*

In short:

s/\.mkv.*/.mkv/s

is:

substitute/<THIS>/<WITH THIS>/s

\.mkv.* matches a literal dot \. then the string mkv and finally any character (including \n for which you need the s flag) zero or more times .*.

Result is replace .mkv<anything> with .mkv.


There is tools to help with reading and building expressions, like https://regex101.com/

ibuprofen
  • 2,890
  • Thanks, that worked perfectly. It was actually a solution I found earlier as well, but wasn't able to make it work. Turns out I was using the rename package that didn't use Perl... oops. – Whiskeyjack May 24 '21 at 00:34
  • @Whiskeyjack: Yeah. Thought of mentioning it, but did not at first (bad of me), updated with more detail for others. – ibuprofen May 24 '21 at 01:01
1

With zsh's zmv:

autoload zmv
zmv -v '(*.mkv)*' '$1'

Removes the part after the rightmost occurrence of .mkv in the filename (renames foo.mkv-bar.mkv-whatever to foo.mkv-bar.mkv).

For the leftmost occurrence (to rename that file to foo.mkv instead), you could replace *.mkv with *.mkv~*.mkv?* which matches a string ending in .mkv but which also otherwise does not contain .mkv followed by at least one character using the ~ "except" glob operator.

1

in bash:

for f in *; do [[ "$f" =~ ^.+\.mkv ]] && mv "$f" "${BASH_REMATCH[0]}"; done
0

In a script bash

#!/bin/bash
for i in *.mkv*
do
  j=$(echo "$i" | sed -e 's/\.mkv.*$/.mkv/')
  mv -- "$i" "$j"
done
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
Shōgun8
  • 711