P
P
Pavel2020-05-30 00:54:47
bash
Pavel, 2020-05-30 00:54:47

How to write a bash script to compare and select filenames containing a number in the name?

I'm looking for information or ready-made solutions.
Supposedly there are several files (one, two or more) named:

  • core-v43.jar
  • core-v44.jar
  • core-v93.jar

You need to enter the name of the file with the largest number in a variable, and delete the rest of the files. If I'm lucky, I hope to find some information for the cmd/bat implementation as well.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Saboteur, 2020-05-30
@saboteur_kiev

VARIABLE=$(ls -v1 *.jar |tail -n1)
find . -name "*.jar" ! -name "$VARIABLE" -delete

V
Viktor Taran, 2020-05-30
@shambler81

5ed20a1026f7c689476589.png
Since the default sorting of ls suits us, we can shorten it.
sort -n - must be used when there are files like 0001 - normal files are here and they will be sorted as expected.

find . -name "*.jar" ! -name "$(ls -1 *.jar | head -n1)"  -delete

If the option is sorted by creation date, then here you can make it even shorter.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question