Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script best way to remove files not in a pair

I have a set of files that come in pairs:

/var/log/messages-20111001
/var/log/messages-20111001.hash

I've had several of these rotate away and now I'm left with a ton of /var/log/messages-201110xx.hash files with no associated log. I'd like to clean up the mess, but I'm uncertain how to remove a file that isn't part of a "pair". I can use bash or zsh (or any LSB tool, really). I need to remove all the .hash files that don't have an associated log.

Example

/var/log/messages-20111001.hash
/var/log/messages-20111002.hash
/var/log/messages-20111003.hash
/var/log/messages-20111004.hash
/var/log/messages-20111005
/var/log/messages-20111005.hash
/var/log/messages-20111006
/var/log/messages-20111006.hash

Should be reduced to:

/var/log/messages-20111005
/var/log/messages-20111005.hash
/var/log/messages-20111006
/var/log/messages-20111006.hash
like image 563
shadowland Avatar asked Dec 31 '25 13:12

shadowland


2 Answers

for file in *.hash; do test -f "${file%.hash}" || rm -- "$file"; done
like image 58
William Pursell Avatar answered Jan 02 '26 07:01

William Pursell


Something like this?

for f in /var/log/messages-????????.hash ; do
    [[ -e "${f%.hash}" ]] || rm "$f"
done
like image 44
Michael Krelin - hacker Avatar answered Jan 02 '26 09:01

Michael Krelin - hacker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!