1.4 Bash Examples
1. Renaming Files
1.1 Using rename
Command
The rename
command in Linux allows you to rename multiple files using regular expressions or patterns. To rename all .htm
files in a directory to .html
, you can use the following command:
rename 's/\.htm$/.html/' *.htm
- Explanation:
's/\.htm$/.html/'
: This is a regular expression substitution pattern that matches files ending with.htm
and replaces the.htm
extension with.html
.*.htm
: This specifies all.htm
files in the current directory.
1.2 Writing a Bash Script
You can also write a bash script to perform this task. Here’s a simple bash script that renames all .htm
files to .html
in the current directory.
Script: rename_htm_to_html.sh
#!/bin/bash
# Loop through all .htm files in the current directoryfor file in *.htm; do # Check if there are any .htm files if [[ -f "$file" ]]; then # Rename the file by changing .htm to .html mv "$file" "${file%.htm}.html" echo "Renamed: $file to ${file%.htm}.html" fidone
for file in *.htm; do
: Loops over all.htm
files in the current directory.if [[ -f "$file" ]]; then
: Checks if the file exists (to avoid errors in case there are no.htm
files).mv "$file" "${file%.htm}.html"
: Renames the file.${file%.htm}
removes the.htm
extension, and then.html
is added.echo "Renamed: $file to ${file%.htm}.html"
: Prints the old and new filenames to confirm the renaming.done
: Ends the loop.
Steps to Use the Script
- Save the script in a file named
rename_htm_to_html.sh
. - Give it executable permissions:
Terminal window chmod +x rename_htm_to_html.sh - Run the script:
Terminal window ./rename_htm_to_html.sh
This will rename all .htm
files in the directory to .html
.