1

I'm trying to create a bash script that takes a directory full of files (about 500 files) that have all different types of extensions (no seriously, like 30 different types of extensions) and I want get rid of all of the extensions, and replace them with .txt

I've been searching around for a while now, and can only find examples of taking a specified extension, and changing it to another specified extension. Like png --> jpg, or .doc --> .txt

Here's an example I've found:

# Rename all *.txt to *.text
for f in *.txt; do 
mv -- "$f" "${f%.txt}.text"
done

This works, but only if you go from .txt to .text, I have multiple different extensions I'm working with.

My current code is:

directory=$1
for item in $directory/*
do
echo mv -- "$item" "$item.txt";
done

This will append the .txt onto them, but unfortunately I am left with the previous ones still attached. E.G. filename.etc.txt, filename.bla.txt

Am I going about this wrong? Any help is greatly appreciated.

2
  • Why not using regex? Commented Sep 19, 2017 at 5:27
  • my knowledge of regex is very limited, could you elaborate? Commented Sep 19, 2017 at 5:44

1 Answer 1

1

It's a trivial change to the first example:

cd "$directory"
# Rename all files to *.txt
for f in *
do 
    mv -- "$f" "${f%.*}.txt"
done

If a file contains multiple extensions, this will replace only the last one. To remove all extensions, use %% in place of %.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! That worked great, but I'm not understanding whats happening inside the move function, what does the %.* do to change the situation?
Read the "Pattern Matching" section of the bash(1) man page or documentation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.