2

I'm trying to rename a lot of videos downloaded via youtube-dl from various sources. As you may know, yt-dl will append the view code to the file name.

E.g.

Video Title-dQw4w9WgXcQ.mp4

I'm looking for a program or CLI command for removing the X last characters from the filename. From the example, the number would be 12 characters (excluding file extension, .mp4)

I've tried searching around for such a command, but havent found any which worked. Also tried KReename, but could not find the equivalent of "Delete X characters starting at Last character", which I remember a Windows program I once used had.

Are there any "simple" commands with which to do this? Alternatively a program, or some setting in KRename. Tried PyRename, but no luck there either.

2

With prename(Perl rename) command:

prename 's/(.*).{12}(\.mp4)/$1$2/' *.mp4
1

With zsh:

autoload zmv # best in ~/.zshrc
zmv -n '(*)?(#c12).mp4' '$1.mp4'

(remove -n (dry-run) when happy).

1

One way to think of this is you want to remove the last 16 characters including extension, so you could use bash parameter expansion to do this:

${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.

Given the part about needing a space after the colon for negative numbers, you can do this:

#!/bin/bash

for f in *mp4; do
   mv -- "$f" "${f:0: -16}.mp4"
done

exit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.