Post

Find and Compress Files in Linux

If you need to free up some space you can use this script to find and compress files in linux. In my case I had some simulation files that were not currently needed, but I didn’t want to get rid of them completely.

A Simple Bash Script

This simple script just looks through the whole of the current directory for files of the type “.ohf”. I used this script to free up disk space, but if you just wanted to compress the files you can just delete or comment out that line.

1
2
3
4
5
6
7
8
9
#!/bin/bash
# Find all ohf files.
# Put them into a tar ball in the directory they were found
find ./ -type f -name "*.ohf" -execdir tar -rvf ohf_archive.tar {} \
# Find all ohf_archive.tar file
# compress them
find ./ -type f -name "ohf_archive.tar" -execdir gzip {} \;
# Find all ohf files again and delete them
find ./ -type f -name "*.ohf" -execdir rm -rf {} \;

A More Flexible Modification

In most cases I think a simple script like the one above will be enough, but it’s easy to add a couple of changes to make it more flexible. Here I’ve added the ability to specify the file type from the command line, and what the output file name should be.

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/bash
# Usage: myzip.sh filetype archive_name
# Find all ohf files.
# Put them into a tar ball in the directory they were found
files="*$1"
tarfile="$2.tar"
find ./ -type f -name "$files" -execdir tar -rvf  "$tarfile" {} \;
# Find all ohf_archive.tar file
# compress them
find ./ -type f -name $tarfile -execdir gzip {} \;
echo "Output to $tarfile"
# Find all ohf files again
find ./ -type f -name $1 -execdir rm -rf {} \;
This post is licensed under CC BY 4.0 by the author.