BASH Programming

How to Loop Over Files in Directory and Change Path and Add Suffix to Filename-Bash

As a programmer, it is common to work with files and directories in a Linux environment and in many cases, you may need to loop over files in a directory, change the path of a file, and add a suffix to the filename. This article will guide you through the process of looping over files in a directory and making changes to the filenames using Bash scripting.

Loop over Files in Directory and Change Path and Add Suffix to Filename

Looping over files in a directory along with changing path and adding suffix to filename is a useful way to automate tasks and make them more efficient. To loop over files in a directory, one can use the for loop command in Bash.

This loop will iterate over all files in the directory, allowing the user to apply commands to each file. For example, one can use the mv command to change the path of the file, or the cp command to make a copy of the file with a different name.

Additionally, one can use the basename command to add a suffix to the filename and to illustrate further below is the code that loops over file in the specified directory along with adding suffix and changing their location:

#!/bin/bash

# Set the path to the source directory

src_dir="/home/aaliyan/Documents"

# Set the path to the destination directory

dest_dir="/home/aaliyan/NewDocuments"

# Loop over each file in the source directory

for file in "$src_dir"/*; do

# Get the filename without the path

filename=$(basename "$file")

 

# Add the suffix to the filename

new_filename="${filename}_new"

 

# Set the path to the destination file

dest_file="$dest_dir/$new_filename"

 

# Move the file to the destination directory with the new filename

mv "$file" "$dest_file"

done

This Bash script loops over each file in a specified source directory and renames it with a suffix “_new” before moving it to a desired directory. The script starts by setting the path to the source and destination directories. It then loops over each file in the source directory, gets the filename without the path, adds the suffix “_new” to the filename and sets the path to the destination file. This script can be useful for renaming and moving many files at once.

Conclusion

This article shows you how to loop over files in a directory, change the path of a file, and add a suffix to a filename using Bash scripting. By combining these techniques, you can easily make changes to multiple files in a directory with just a few lines of code.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.