How do I truncate the last two characters of all f

2019-09-21 19:56发布

问题:

This question already has an answer here:

  • Bash script to remove 'x' amount of characters the end of multiple filenames in a directory? 3 answers

So pretty simple question. All of the files in my directory are of the form 6bfefb348d746eca288c6d62f6ebec04_0.jpg. I want them to look like 6bfefb348d746eca288c6d62f6ebec04.jpg. Essentially, I want to take off the _0 at the end of every file name. How would I go about doing this with bash?

回答1:

With Perl's standalone rename command:

rename -n 's/..(\....)$/$1/' *

If everything looks fine, remove -n.


It is possible to use this standalone rename command with a syntax similar to sed's s/regexp/replacement/ command. In regex a . matches one character. \. matches a . and $ matches end of line (here end of filename). ( and ) are special characters in regex to mark a subexpression (here one . and three characters at the end of your filename) which then can be reused with $1. sed uses \1 for first back-reference, rename uses $1.

See: Back-references and Subexpressions with sed