Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux: remove file extensions for multiple files

Tags:

linux

bash

rename

I have many files with .txt extension. How to remove .txt extension for multiple files in linux?

I found that

rename .old .new *.old 

substitutes .old extension to the .new

Also I want to do this for files in sub-folders.

like image 721
rp101 Avatar asked Dec 22 '10 13:12

rp101


People also ask

How do I remove multiple file extensions in Linux?

In Unix-like operating systems such as Linux, you can use the mv command to rename a single file or directory. To rename multiple files, you can use the rename utility. To rename files recursively across subdirectories, you can use the find and rename commands together.

How do I remove all file extensions from a folder in Linux?

Using rm Command The 'rm' command is a basic command-line utility in Linux to remove sockets, pipes, device nodes, symbolic links, directories, system files, etc. To remove a file with a particular extension, use the command 'rm'. This command is very easy to use, and its syntax is something like this.


2 Answers

rename is slightly dangerous, since according to its manual page:

rename will rename the specified files by replacing the first occurrence of...

It will happily do the wrong thing with filenames like c.txt.parser.y.

Here's a solution using find and bash:

find -type f -name '*.txt' | while read f; do mv "$f" "${f%.txt}"; done 

Keep in mind that this will break if a filename contains a newline (rare, but not impossible).

If you have GNU find, this is a more solid solution:

find -type f -name '*.txt' -print0 | while read -d $'\0' f; do mv "$f" "${f%.txt}"; done 
like image 124
thkala Avatar answered Sep 20 '22 06:09

thkala


I use this:

find ./ -name "*.old" -exec sh -c 'mv $0 `basename "$0" .old`.new' '{}' \; 
like image 24
Chris Cowan Avatar answered Sep 19 '22 06:09

Chris Cowan