linux  scripts

KeepByCount

KeepByCount _PATH _COUNT _FILTER
_PATH: Path
_COUNT: Count of files to keep
_FILTER: Filter for files
#!/bin/bash

# sudo nano -n /usr/local/bin/KeepByCount.sh
# sudo chmod +x /usr/local/bin/KeepByCount.sh

#Usage in other scripts
# source /usr/local/bin/KeepByCount.sh

#Usage by command line
#!!Uncomment: Last line in this script

#KeepByCount _PATH _COUNT _FILTER
# _PATH: Path
# _COUNT: Count of files to keep
# _FILTER: Filter for files
#
#Example
# KeepByCount "/media/nas1week/nas" 5 "*.7z"
# KeepByCount "/media/nas1week/nas" 5 "*_FULL.7z"
# KeepByCount "/media/nas1week/nas" 5 "*_INCREMENT.7z"
KeepByCount() {
    #Parameters
    _PATH=$1
    _COUNT=$2
    _FILTER=$3

    cd "${_PATH}" || {
        echo "Directory not found: ${_PATH}"
        exit 1
    }
    tmp=$(ls -l ${_FILTER} 2>/dev/null | wc -l)
    if [ "${tmp}" != "0" ]; then
        ls ${_FILTER} | head -n -${_COUNT} >/tmp/_file.lst
        while read -r LINE; do
            rm ${LINE}
        done </tmp/_file.lst

        rm /tmp/_file.lst
    fi
}

#KeepByCount "$1" "$2" "$3"