UNIX: Loop Through Files In A Directory

In Unix-like systems, you can use a for loop to iterate through all of the files in a directory. Here’s an example of a simple bash shell script that loops through all of the files in the current directory:

for file in *; do
echo "$file"
done

In this example, the * wildcard matches all files in the current directory, and the for loop iterates over each file. The echo command is used to display the name of each file.

You can modify the script to perform any action you like on each file, such as moving, copying, or deleting the file, or processing its contents in some way.

Here’s an example of a script that moves all .txt files in the current directory to a subdirectory called text_files:

for file in *.txt; do
mv "$file" text_files/
done

In this example, the for loop iterates over all .txt files in the current directory, and the mv command is used to move each file to the text_files subdirectory.

You can use this same basic pattern to loop through files in any directory, by replacing the * wildcard with the path to the desired directory. For example, to loop through all of the files in the /tmp directory, you could use the following script:

for file in /tmp/*; do
echo "$file"
done

Leave a Comment