I want to compare two files in a folder and delete the number in the name which is the smaller of the two.

For instance, say the names were yearMonthDay.txt. I want to compare which is a smaller number and sudo rm it.

I know I can get the numbers via:

find *txt | awk -F'[_.]' '{ print $1}'

How then next should I compare it? Using system variables? I actually haven't used shell variables before.

  • You can set variables, for example var1=$(command-to-print-filename-1) etc and then compare the sizes in an if command. But you can also sort the files with sort and select the first file with head or the last file with tail and that way decide what to keep and what to remove.
    – sudodus
    Nov 27, 2021 at 2:53
  • @sudodus, thanks, I think I got it: eval $(printf "rm file_"$(find *txt | awk -F'[_.]' '{ print $2}' | sort -r | tail -1)".txt")
    – 1toneboy
    Nov 27, 2021 at 6:49

1 Answer 1


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
./2020 131.txt

The following command line uses stat to help the find-list of txt-files,

$ find -name '*.txt' -exec stat -c '%N' {} \;
'./2020 131.txt'

Now sort it (can be done without removing the extension)

$ find -name '*.txt' -exec stat -c '%N' {} \; | sort
'./2020 131.txt'

and select the oldest one (at the top of the list)

$ find -name '*.txt' -exec stat -c '%N' {} \; | sort | head -n1

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


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" ]
 eval rm "$var1"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .