I need help with a bash script that loops through a directory and its subdirectories,…
- User
I need help with a bash script that loops through a directory and its subdirectories, looking for files with a specific extension (e.g., .txt). For each file found, the script should extract the date it was last modified, and create a new directory named after that date (if it doesn't already exist). The script should then move the file into the directory named after its modification date. Can you help me write this script in bash?
- Assistant
Sure, here's a script that does what you described:
bash
#!/bin/bash
specify the extension of the files you want to look for
extension=".txt"
loop through all files in the current directory and its subdirectories
for file in extension") do # extract the date the file was last modified date=file" +%Y-%m-%d)
- User
Thank you! :) Is this script safe also with filenames / paths that contain spaces or other special characters?
- Assistant
This script may not work correctly with filenames or paths that contain spaces or other special characters. To handle these cases, you need to use quotes around variables that contain spaces or special characters.
Here is an updated version of the script that properly handles filenames and paths with spaces and special characters:
bash
#!/bin/bash
specify the extension of the files you want to find
extension=".txt"
loop through all files in the directory and its subdirectories
find . -type f -name "*$extension" | while read file; do
get the date the file was last modified
date=file" +%Y-%m-%d)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →