简体   繁体   中英

One-line way to remove last n characters from string

I have a bunch of files in the format photo.jpg.png in a folder, and for every photo in this folder, I want to replace the .jpg.png with .png . How can I do this from Terminal?

I have a basic Python and bash background, so I know I'd want to do something like this:

 $ for i in *.png; do mv $i $i[:-8]; done
 $ for i in *; do mv $i $i.png; done

But what would I replace the Pythonic [:-8] with in order to remove the last 8 characters of each filename?

EDIT I now realize that a substring that counts from the end of the string would be superior. Is there a way to do this as well?

You can use pattern expansion:

for f in *.jpg.png; do mv -v "$f" "${f/.jpg.png/.png}"; done

Though you might still have problems with a filename like foo.jpg.png.gif .

If you really want to strip the last 7 or 8 characters, you can use a substring expansion:

for f in *.jpg.png; do mv -v "$f" "${f:0:-7}png"; done

Note that use of negative numbers in substring length requires bash version 4 or higher.

With Perl's standalone rename command:

rename -n 's/jpg\.png$/png/' *.jpg.png

or

rename -n 's/.......$/png/' *.jpg.png

Output:

rename(photo.jpg.png, photo.jpg)

If everything looks okay, remove `-n'.

rename is designed for this kinda thing;

$ rename .jpg.png .png *.jpg.png

For MacOS, I realized that rename may not be available by default, you can install it using brew .

$ brew install rename

and then use -s option for rename ;

$ rename -s .jpg.png .png *.jpg.png

Removing the last 8 characters using perl's rename :

$ rename -n 's/.{8}$//' *.png

(remove -n switch when your tests are OK)
or with :

for i in *.png; do
    echo mv "$i" "${i:0:-8}"
done

(remove echo when your tests are OK)

警告 There are other tools with the same name which may or may not be able to do this, so be careful.

If you run the following command ( GNU )

$ file "$(readlink -f "$(type -p rename)")"

and you have a result like

.../rename: Perl script, ASCII text executable

and not containing:

ELF

then this seems to be the right tool =)

If not, to make it the default (usually already the case) on Debian and derivative like Ubuntu :

$ sudo update-alternatives --set rename /path/to/rename

(replace /path/to/rename to the path of your perl's rename command.


If you don't have this command, search your package manager to install it or do it manually


Last but not least, this tool was originally written by Larry Wall, the Perl's dad.

Something like that:

$ v=test.jpg.png
$ echo ${v:0:-8}
test

这应该工作:

for file in *.jpg.png; do mv $file ${file//jpg.png/jpg} ; done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM