change file extension linux

How to Change File Extension of Multiple Files in Linux

Sometimes you may get many files with a particular extension and may need to change it to another file extension. For example, you have received hundreds of .txt files and may need to change them to .csv files. It can be tedious if you do this manually. It is advisable to use a command or script for this purpose. Luckily in Linux there are many ways to change file extension of multiple files. In this article, we will learn how to change file extension of multiple files in Linux using mv command.

How to Change File Extension of Multiple Files in Linux

Let us say you have many .txt files in a folder /home/ubuntu. Here is a simple shell code to change extension of all .txt files to .csv.

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

In the above command, we use *.txt to match all .txt files in /home/ubuntu. We use — (double hyphen) to indicate end of options, to avoid conflicts with filenames that begin with hyphen.

${f%.txt} is a parameter expansion which is replaced by the value of the f variable with .txt removed from the end.

Alternatively, you can also use basename command to get filename without extension.

for f in /home/ubuntu/*.txt; do
    mv -- "$f" "$(basename -- "$f" .txt).text"
done

You can even create a small shell script to easily work on all file locations. Create an empty shell script.

$ vi change_ext.sh

Add the following lines to it.

#!/bin/sh

for f in $1/*.txt; do 
    mv -- "$f" "${f%.txt}.csv"
done

Save and close the file. In the above shell script, we use the first argument $1 to get file location.

Make it an executable with the following command.

$ chmod +x change_ext.sh

You can run the shell script followed by folder location of your text files whose extension you want to change. Here is an example to change file extension from .txt to .csv in /home/data folder.

$ sh ./change_ext.sh /home/data

In this article, we have learnt a couple of simple ways to easily change extension of multiple files in Linux.

Also read:

How to Remove HTML Tags from CSV File in Python
How to Convert PDF to CSV in Python
How to Convert PDF to Text in Python
How to Convert Text to CSV File in Python
How to Split List Into Even Chunks

Leave a Reply

Your email address will not be published. Required fields are marked *