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.htmand replaces the.htmextension with.html.*.htm: This specifies all.htmfiles 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" fidonefor file in *.htm; do: Loops over all.htmfiles in the current directory.if [[ -f "$file" ]]; then: Checks if the file exists (to avoid errors in case there are no.htmfiles).mv "$file" "${file%.htm}.html": Renames the file.${file%.htm}removes the.htmextension, and then.htmlis 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.