Monday, January 20, 2025
HomeProgrammingBash - How To Loop Over Files In Directory

Bash – How To Loop Over Files In Directory

In Bash, you can loop over the files in a directory and change their path or perform operations on them. Here’s how you can do this using a for loop or find command, depending on your needs.

Example 1: Using for loop to loop over files and change path

Suppose you want to loop over all files in a directory and change the path to a new directory.

#!/bin/bash

# Define the source and destination directories
source_dir="/path/to/source"
destination_dir="/path/to/destination"

# Loop through all files in the source directory
for file in "$source_dir"/*; do
  if [[ -f "$file" ]]; then
    # Move or change path of each file to the new directory
    mv "$file" "$destination_dir/"
    echo "Moved $file to $destination_dir/"
  fi
done

In this example:

  • "$source_dir"/* lists all files in the source directory.
  • The if [[ -f "$file" ]] checks if the current item is a file (not a directory).
  • mv "$file" "$destination_dir/" moves each file to the new path.
See also  String comparison in Python: is vs. == [duplicate]

Example 2: Using find command to loop over files and change path

If you want to apply the operation recursively to all files in subdirectories as well, find can be a better option.

#!/bin/bash

# Define the source and destination directories
source_dir="/path/to/source"
destination_dir="/path/to/destination"

# Use find to loop through all files in the source directory
find "$source_dir" -type f | while read file; do
  # Move each file to the new directory
  mv "$file" "$destination_dir/"
  echo "Moved $file to $destination_dir/"
done

In this example:

  • find "$source_dir" -type f lists all files (not directories) in the source directory and its subdirectories.
  • The while read file reads each file path from the output of find.
  • mv "$file" "$destination_dir/" moves each file to the new directory.
See also  Simplest Way to Print a Java Array

Both approaches allow you to loop through files in a directory and change their path as needed. The first method is suitable for simple directories, while the second method is more flexible for recursive operations.

RELATED ARTICLES

Banking Application in Java

Java PrintWriter Class

What Is CSS Hover?

0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x