An admittedly brittle solution that uses bash arrays:
#!/bin/bash
workdir='/home/haxiel/testdir'
prefixes=( $(ls $workdir | cut -d '_' -f 1-3 | sort | uniq) )
for prefix in ${prefixes[@]}; do
files=( $workdir/$prefix* )
unset files[0]
echo rm -- ${files[@]}
done
I'm using the ls|cut|sort|uniq
pipe to build a list of unique prefixes.
Then I loop through the prefixes and use shell globbing to grab all files that match a certain prefix and store it in an array. You want to keep the first one, so I remove that file from the array and pass the rest to an rm
command.
This solution assumes that you have filenames without special characters. It also assumes that the shell's sort order matches your expected sort order.
Be sure to put the script outside of the working directory. Otherwise, the script name gets captured as one of the prefixes.
Run this once and examine the output to make sure that you're removing the right files. Then, remove the 'echo' command in front of rm
and run it once again.
As always, data removal is a risky process, so use caution and have a backup if you think you'll need it.