Can you help me write a shell script for the following: I have a folder /data/ in which many folders are found with different names. For each of these folders, I want to delete all the files in them EXCEPT one file called ids*.bin, where * is the largest integer value found in the specific folder. This ids*.bin file I want to rename to ids0.bin, while all the other files can be deleted.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Below is a robust Bash script that will do exactly what you asked:
• For every direct child directory of /data/
• Keep the ids*.bin file that has the highest integer suffix
• Rename that file to ids0.bin
• Delete every other file inside that directory (including other ids*.bin files)
bash
#!/usr/bin/env bash
#
# keep-largest-ids.sh
# -------------------
# For each sub-directory of /data/:
# 1. Find the ids*.bin file with the largest numeric suffix
# 2. Delete every other file in that directory
# 3. Rename the kept file to ids0.bin
#
# Safety: the script is quite defensive, but TEST IT on a copy first!
#-------------------------------------------------------------------------
set -Eeuo pipefail # safer bash (exit on failure, undefined vars are errors)
shopt -s nullglob # an unmatched glob expands to nothing, not itself
DATA_DIR="/data"
for dir in "$DATA_DIR"/*/ ; do # loop over every sub-directory
[[ -d $dir ]] || continue # skip if not a directory (just in case)
# -------------------------------
# Step 1. Pick the "largest" ids*.bin
# -------------------------------
ids_files=( "$dir"ids*.bin )
if (( ${#ids_files[@]} == 0 )); then # no ids*.bin? skip this directory
echo "[$dir] - no ids*.bin files, skipping"
continue
fi
# Use sort -V (version sort) to get the highest numeric suffix
# Example order produced: ids1.bin ids2.bin ids11.bin → last one is largest
mapfile -t sorted_ids < <(
printf '%s\n' "${ids_files[@]}" | sort -V
)
largest_file="${sorted_ids[-1]}" # the last entry
echo "[$dir] keeping: $(basename "$largest_file")"
# -------------------------------
# Step 2. Delete everything else
# -------------------------------
# -type f → only files, leave directories alone
# ! -samefile "$largest_file" → everything except the chosen one
find "$dir" -type f ! -samefile "$largest_file" -print -delete
# -------------------------------
# Step 3. Rename kept file to ids0.bin
# -------------------------------
target="$dir"ids0.bin
# If ids0.bin already exists, remove it first (or handle as you like)
[[ -e $target ]] && rm -f -- "$target"
mv -f -- "$largest_file" "$target"
done
echo "✅ All done."
How it works (quick breakdown)
for dir in "$DATA_DIR"/*/ – iterates through each immediate subfolder under /data/.
ids_files=( "$dir"ids*.bin ) – collects every matching file inside that subfolder.
sort -V – “version” sort understands numbers, so ids11.bin sorts after ids2.bin.
find … -delete – removes every file except the one chosen with -samefile.
mv – finally renames the survivor to ids0.bin.
A few optional tweaks
• Want to process sub-directories recursively? Replace the first for loop with a find /data -type d ....
• Prefer a dry-run first? Add echo in front of the find … -delete and mv lines to print what would happen.
• Need logging? Redirect the whole script’s stdout/stderr to a file: ./keep-largest-ids.sh &> /tmp/cleanup.log.
Test run
bash
# Assuming you saved the script as keep-largest-ids.sh
chmod +x keep-largest-ids.sh
./keep-largest-ids.sh
Make sure you test against a copy of your folders first—delete operations are irreversible! 😉
User
You are so right to first ask me to test this! Could you maybe write it with a flag called CHECK_SAFETY that prints the folder, the relative path to the file ids*.bin that will be kept, while the others are deleted? It would be perfect if when I write CHECK_SAFETY=false, that then the files will be removed and the actual deleting is implemented.
Assistant
Below is a single-file solution that supports a “dry-run” mode controlled by the shell variable CHECK_SAFETY.
• If CHECK_SAFETY=true (default) the script ONLY prints what it would keep and delete—nothing is modified.
• If CHECK_SAFETY=false the script does the real work: deletes everything except the largest ids*.bin, then renames that file to ids0.bin.
bash
#!/usr/bin/env bash
#
# cleanup_ids.sh ----------------------------------------------------------
# Keep the largest ids*.bin in each direct sub-directory of /data/
# • Dry-run when CHECK_SAFETY=true (default)
# • Real deletion when CHECK_SAFETY=false
# -------------------------------------------------------------------------
set -Eeuo pipefail
shopt -s nullglob # unmatched globs expand to nothing
DATA_DIR="/data"
CHECK_SAFETY="${CHECK_SAFETY:-true}" # export or override on cmd line
log() { printf '%s\n' "$*"; }
[[ $CHECK_SAFETY == true ]] && log "🔎 SAFETY CHECK MODE (no files will be touched)"
[[ $CHECK_SAFETY == false ]] && log "⚠️ LIVE MODE — files will be deleted!"
for dir in "$DATA_DIR"/*/; do
[[ -d $dir ]] || continue
ids_files=( "$dir"ids*.bin )
(( ${#ids_files[@]} )) || { log "[$dir] no ids*.bin found, skipping"; continue; }
# pick the largest numeric suffix
mapfile -t sorted_ids < <(printf '%s\n' "${ids_files[@]}" | sort -V)
keep_file="${sorted_ids[-1]}"
target="${dir}ids0.bin"
# --------------------------------------------------------------------
# DRY-RUN
# --------------------------------------------------------------------
if [[ $CHECK_SAFETY == true ]]; then
log "📂 ${dir#$DATA_DIR/}"
log " keep : ${keep_file#$DATA_DIR/}"
find "$dir" -type f ! -samefile "$keep_file" -printf ' delete : %P\n'
echo
continue
fi
# --------------------------------------------------------------------
# REAL ACTIONS
# --------------------------------------------------------------------
find "$dir" -type f ! -samefile "$keep_file" -delete
[[ -e $target ]] && rm -f -- "$target"
mv -f -- "$keep_file" "$target"
log "✅ ${dir#$DATA_DIR/} → kept $(basename "$target"), others removed"
done
Usage
Dry-run (recommended first!):
bash
CHECK_SAFETY=true ./cleanup_ids.sh
# or simply: ./cleanup_ids.sh (because true is the default)
Actual cleanup:
bash
CHECK_SAFETY=false ./cleanup_ids.sh
Feel free to tweak DATA_DIR or extend the script (e.g., recursive traversal, logging to a file, etc.). Always test again on a sample dataset before running live on valuable data!