Assuming that the timestamps are not reliable, we'd like to find the file that has the largest number in the parenthesis towards the end of the filename.
Doing that:
#!/bin/sh
prefix=$1
if [ -z "$prefix" ]; then
printf 'Usage: %s prefix [ suffix ]\n' "$0" >&2
exit 1
fi
suffix=$2
for filename in "$prefix ("*")$suffix"; do
[ ! -f "$filename" ] && continue
num=${filename##*\(} # "file (xx).txt" --> "xx).txt"
num=${num%\)*} # "xx).txt" --> "xx"
# if no max number yet, or if current number is higher, update max
if [ -z "$max" ] || [ "$num" -gt "$max" ]; then
max=$num
fi
done
# if we have a max number, use it to rename the file and then remove the other files
if [ -n "$max" ]; then
printf 'Would move %s to %s\n' "$prefix ($max)$suffix" "$prefix$suffix"
# mv "$prefix ($max)$suffix" "$prefix$suffix"
printf 'Would remove %s\n' "$prefix ("*")$suffix"
# rm "$prefix ("*")$suffix"
else
printf 'Found no files matching "%s (*)%s"\n' "$prefix" "$suffix"
fi
Running it:
$ tree
.
|-- file (1).txt
|-- file (2).txt
|-- file (7).txt
|-- file.list
|-- file.txt
`-- script.sh
0 directory, 6 files
$ sh script.sh file .txt
Would move file (7).txt to file.txt
Would remove file (1).txt
Would remove file (2).txt
Would remove file (7).txt
(remove the commented out mv and rm to actually modify files)
This would fail for filenames such as file (2) (30).txt (these would also be matched) as it assumes that all filenames follow the pattern prefix (NN)suffix where NN is an integer.
lsgives me the error, i haven't yet got to the for loop