Shell : Bash shell script that will recursively traverse and replace the file or extension

Shell Scripting @ Freshers.in

Here’s a simple Bash shell script that will recursively traverse through the directory it’s run in and rename all .jpg files to .jpeg.

Shell script:

#!/bin/bash

# Loop through all .jpg files
for file in $(find . -name "*.jpg")
do
    # Get the base name of the file (file name without extension)
    base_name=$(basename "$file" .jpg)

    # Get the directory name of the file
    dir_name=$(dirname "$file")

    # Rename the file by changing its extension to .jpeg
    mv "$file" "$dir_name/$base_name.jpeg"
done

This script uses the find command to locate all .jpg files, and then uses a loop to go through each file one by one. The basename command is used to get the base name of the file (i.e., the file name without the extension), and the dirname command is used to get the directory name of the file. Finally, the mv command is used to rename the file by changing its extension to .jpeg.

Now we need to ignore directories named “movie” or “music” and files starting with “unknown” . This can be performed using the below

#!/bin/bash

# Loop through all .jpg files
for file in $(find . -name "*.jpg" -not -path "./movie/*" -not -path "./music/*")
do
    # Get the base name of the file (file name without extension)
    base_name=$(basename "$file" .jpg)

    # Skip if file starts with 'unknown'
    if [[ $base_name == unknown* ]]; then
        continue
    fi

    # Get the directory name of the file
    dir_name=$(dirname "$file")

    # Rename the file by changing its extension to .jpeg
    mv "$file" "$dir_name/$base_name.jpeg"
done

In the find command, -not -path “./movie/*” and -not -path “./music/*” are added to ignore files inside “movie” and “music” directories. The if condition checks if the base name of the file starts with “unknown” and if it does, it skips the renaming part for that file.

Please note that this script will only ignore “movie” and “music” directories that are directly under the directory from which the script is run. If you want to ignore all “movie” and “music” directories regardless of their depth in the directory tree, replace ./movie/* and ./music/* with */movie/* and */music/* respectively.

Other urls to refer

  1. PySpark Blogs
Author: user

Leave a Reply