I suggest that you make something like the following:
I made a directory with some files with 'normal' date-like names, one file with a space in the name (makes you need quoting) and one file with a new-line in the name (can cause problems, if the commands that you use assume that new-lines separate files).
$ find
.
./20210710.txt
./20200131.txt
./20210611.txt
./2020?0131.txt
./20201131.txt
./2020 131.txt
The following command line uses stat
to help the find
-list of txt-files,
$ find -name '*.txt' -exec stat -c '%N' {} \;
'./20210710.txt'
'./20200131.txt'
'./20210611.txt'
'./2020'$'\n''0131.txt'
'./20201131.txt'
'./2020 131.txt'
Now sort it (can be done without removing the extension)
$ find -name '*.txt' -exec stat -c '%N' {} \; | sort
'./20200131.txt'
'./20201131.txt'
'./2020 131.txt'
'./2020'$'\n''0131.txt'
'./20210611.txt'
'./20210710.txt'
and select the oldest one (at the top of the list)
$ find -name '*.txt' -exec stat -c '%N' {} \; | sort | head -n1
'./20200131.txt'
Now you can remove this file by
rm $(find -name '*.txt' -exec stat -c '%N' {} \; | sort | head -n1)
It there is a risk that there would be a space or other special character, you want to quote it (but check carefully that you avoid conflicts with previous quoting)
rm "$(find -name '*.txt' -exec stat -c '%N' {} \; | sort | head -n1)"
You can also set a variable, and use that in commands later on in a shellscript
#!/bin/bash
find -name '*.txt' -exec stat -c '%N' {} \; | sort
var1=$(find -name '*.txt' -exec stat -c '%N' {} \; | sort | head -n1)
echo '---'
read -p "Remove $var1? (y/N) " ans
if [ "$ans" == "y" ]
then
eval rm "$var1"
fi
var1=$(command-to-print-filename-1)
etc and then compare the sizes in anif
command. But you can also sort the files withsort
and select the first file withhead
or the last file withtail
and that way decide what to keep and what to remove.