Sujet : Re: Script to conditionally find and compress files recursively
De : jenniferkatenewman (at) *nospam* gmail.com (J Newman)
Groupes : comp.os.linux.miscDate : 15. Jun 2024, 04:30:35
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v4j1sp$39rdv$1@dont-email.me>
References : 1
User-Agent : Mozilla Thunderbird
On 11/06/2024 14:53, J Newman wrote:
Hi, I'm interested in writing a script that will:
1. Find and compress files recursively
2. After the first 5 seconds of compressing, if the compression ratio >1 (i.e. the compressed file will be larger than the uncompressed file), it tries another compression algorithm.
3. If the other compression algorithm still has a ratio >1, it tries another algorithm, until a list is exhausted.
4. If the list is exhausted, it skips compressing that file.
Any suggestions on how to proceed?
This is the script ChatGPT gives. After some thought, I decided to just go with one compression algorithm for simplicity, and just not compress the files if the compression ratio >1.
#!/bin/bash
# Function to compress a file with lzma and keep it only if compression ratio is <1
compress_file() {
local file=$1
local orig_size=$(stat --printf="%s" "$file")
# Compress with lzma
lzma -z -k -c "$file" > "$file.lzma"
local lzma_size=$(stat --printf="%s" "$file.lzma")
# If the lzma compressed file is smaller than the original, keep it
if (( lzma_size < orig_size )); then
mv "$file.lzma" "$file.compressed"
echo "File compressed using lzma: $file -> $file.compressed"
else
rm -f "$file.lzma"
echo "No compression applied for $file as the compressed size was not smaller than the original."
fi
}
# Export the function so it's available to find -exec
export -f compress_file
# Recursively find all files and compress them
find . -type f -exec bash -c 'compress_file "$0"' {} \;
echo "Compression process complete."