Skip to content

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:

Terminal window
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 directory
for 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"
fi
done
  1. for file in *.htm; do: Loops over all .htm files in the current directory.
  2. if [[ -f "$file" ]]; then: Checks if the file exists (to avoid errors in case there are no .htm files).
  3. mv "$file" "${file%.htm}.html": Renames the file. ${file%.htm} removes the .htm extension, and then .html is added.
  4. echo "Renamed: $file to ${file%.htm}.html": Prints the old and new filenames to confirm the renaming.
  5. done: Ends the loop.

Steps to Use the Script

  1. Save the script in a file named rename_htm_to_html.sh.
  2. Give it executable permissions:
    Terminal window
    chmod +x rename_htm_to_html.sh
  3. Run the script:
    Terminal window
    ./rename_htm_to_html.sh

This will rename all .htm files in the directory to .html.