Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

How to change/remove the file extensions of a group of files

Writer Emily Wong

I have a bunch of .txt files in a directory, and I want to be able to find these files and strip the extension from the file name.

I can find the files using:

$ find . -maxdepth 1 -type f -name "*.txt"
./0test.txt
./1test.txt
./2test.txt
./3test.txt
./4test.txt
./5test.txt
./6test.txt
./7test.txt
./8test.txt
./9test.txt

I then tried to use sed command to remove the ".txt" extension, like:

find . -maxdepth 1 -type f -name "*.txt" | sed "s/\.txt$//"

But I just get the file names listed without their extensions, and the actual file names remain unchanged.

So how do you actually change the file names themselves?

3 Answers

How about this in bash

for v in *.txt ; do mv "$v" "$(basename "$v" .txt)"; done
3

$ in a regular expression matches the end of a string, you can't match characters after that, only before.

Also . needs to be escaped to stop it from having its special meaning (any character).

So:

find . -maxdepth 1 -type f -name "*.txt" | sed "s/\.txt$//"

If you're trying to rename the files, then you can use the same regular expression substitution with the perl-based rename command

rename "s/\.txt$//" *.txt

(you don't need find when all the files are in a single directory level), or a simple shell loop with mv:

for f in *.txt; do mv -n -- "$f" "${f%.txt}"; done
4

I know that this is an old question, maybe someone will benefit from this. Last night I needed to do this exact thing with sed, I asked God to show me, I had been trying this :echo filename.txt | sed 's/\.*$// and it just didn't work, it presented the filename including extension as is. This is what God revealed echo filename.txt | sed 's/\...*$//' filename

This removes not only 3 letter extensions but multiple extensions ie. tar.bz2, tar.xz and even tar.gz also.

echo filename.txt | sed 's/\...*$//' filename
echo filename.epub | sed 's/\...*$//' filename
echo filename.tar.xz | sed 's/\...*$//' filename
echo filename.tar.bz2 | sed 's/\...*$//' filename
echo filename.txt.gz| sed 's/\...*$//' filename

This also has the desired result:

echo filename.txt | sed 's/\..*//' filename

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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