File Manipulation Script: Renames, Moves, or Deletes Files in Bulk
In this tutorial, we will learn how to create a simple file manipulation script in Bash to rename, move, or delete files in bulk.
Before we begin, you should have access to a Unix/Linux system with Bash installed, and have basic knowledge of shell scripting and the mv and rm commands.
2. Creating the File Manipulation Script
Let’s start by creating a new script file using a text editor of your choice. We’ll call the script file_manip.sh.
#!/bin/bash # Define the source and destination directories src_dir="~/files" dst_dir="~/archives" # Define the file extension to manipulate file_ext=".txt" # Loop through all files with the specified extension in the source directory for file in $src_dir/*$file_ext; do # Get the filename without the path filename=$(basename $file) # Rename the file by adding the current date to the filename mv $file $src_dir/$filename-$(date +%Y%m%d) done # Move the renamed files to the destination directory mv $src_dir/*$file_ext $dst_dir # Print a message indicating that the file manipulation is complete echo "File manipulation complete!"
3. Explanation of the Script
The script starts with the shebang line #!/bin/bash, which indicates that the script should be interpreted by the Bash shell.
Next, we define two variables: src_dir and dst_dir. These variables specify the source and destination directories for the file manipulation. In this example, the source directory is ~/files and the destination directory is ~/archives.
We also define a variable file_ext that specifies the file extension to manipulate. In this example, we will manipulate files with the .txt extension.
We then use a for loop to iterate through all files with the specified extension in the source directory. For each file, we use the basename command to get the filename without the path. We then use the mv command to rename the file by adding the current date to the filename.
After all the files have been renamed, we use another mv command to move the renamed files to the destination directory.
Finally, we print a message indicating that the file manipulation is complete using the echo command.
4. Running the File Manipulation Script
Now that we have created the file manipulation script, we can run it by making it executable and executing it in the terminal:
chmod +x file_manip.sh
The script will run and rename, move, or delete the specified files in the source directory.
5. Customizing the File Manipulation Script
You can customize the script to meet your specific needs by changing the source and destination directories, file extension, and file manipulation actions. For example, to delete files instead of moving them, you can replace the mv command in the script with the rm command.
That’s it! You now know how to create a file manipulation script in Bash to rename, move, or delete files in bulk. The script can be a useful tool for automating repetitive file management tasks.