How would you write a script that searches for all files in a directory with a specific file extension and move them to a new directory?&#8221

1 Answers
Answered by suresh

Script to Search and Move Files with Specific Extension

Focus Keyword: Script to move files with specific extension in directory

How to Write a Script to Search and Move Files with Specific Extension

In order to move files with a specific file extension to a new directory, you can write a script using programming languages like Python or Bash.

Python Script


import os
import shutil

source_directory = 'path/to/source_directory'
target_directory = 'path/to/target_directory'
file_extension = '.jpg'

for file_name in os.listdir(source_directory):
    if file_name.endswith(file_extension):
        source_path = os.path.join(source_directory, file_name)
        target_path = os.path.join(target_directory, file_name)
        shutil.move(source_path, target_path)

Bash Script


source_directory="path/to/source_directory"
target_directory="path/to/target_directory"
file_extension=".jpg"

find $source_directory -name "*$file_extension" -type f -exec mv -t $target_directory {} +

By running the above scripts with the appropriate paths and file extension, you can efficiently search for all files with the specified extension in a directory and move them to a new destination.

Answer for Question: How would you write a script that searches for all files in a directory with a specific file extension and move them to a new directory?&#8221