How to replace spaces in file names using bash script on Linux?

LinuxOperating SystemOpen Source

Consider a case in which one directory on my local machine looks something like this −

immukul@192 dir1 % ls -ltr
total 0
-rw-r--r-- 1 immukul staff 0 Jul 3 20:44 sample code.txt
-rw-r--r-- 1 immukul staff 0 Jul 3 20:44 sample code with love.txt

In the above directory named dir1, there are two .txt files present and both these files have spaces in between the words in their name, and we need to replace these spaces using a bash script on Linux.

In order to achieve what we want, we must first be aware of the fact that we can traverse the files via a Linux command and print their names, then we can later modify that command to replace the spaces in the files name to _ and get the desired output.

To print the spaces in the files names we just need to type the following command in the terminal −

for f in *.txt; do echo ${f}; done;

Output

immukul@192 dir1 % for f in *.txt; do echo ${f}; done;

sample code with love.txt
sample code.txt

Now, we just need to modify the part after the first semicolon to allow us to replace the spaces with the underscores.

The command for that is −

for file in *.txt; do mv "$file" "${file// /_}"; done

In the above command, we are iterating over all the files that are matching the .txt extension then we are taking one file at a time and then moving it to a new file, to get the new name, and in that new name we are replacing the spaces in between the file names to underscores.

Output

immukul@192 dir1 % ls -tlr
total 0
-rw-r--r-- 1 immukul staff 0 Jul 3 20:44 sample_code.txt
-rw-r--r-- 1 immukul staff 0 Jul 3 20:44 sample_code_with_love.txt

A better way is to put the command into a bash script and then run that bash script.

To create a bash script, create a file named sample.sh and then give it all the permissions to make it into an executable.

touch sample.sh
chmod 777 sample.sh

Now put the command inside the sample.sh file and execute the file using the following command −

./sample.sh

Output

immukul@192 dir1 % ls -tlr
total 0
-rw-r--r-- 1 immukul staff 0 Jul 3 20:44 sample_code.txt
-rw-r--r-- 1 immukul staff 0 Jul 3 20:44 sample_code_with_love.txt
raja
Published on 30-Jul-2021 09:09:24
Advertisements