Shenan
Shenan

Reputation: 545

How can I delete the directory with the highest number name?

I have a directory containing sub-directories, some of whose names are numbers. Without looking, I don't know what the numbers are. How can I delete the sub-directory with the highest number name? I reckon the solution might sort the sub-directories into reverse order and select the first sub-directory that begins with a number but I don't know how to do that. Thank you for your help.

Upvotes: 2

Views: 240

Answers (3)

Petr Skocik
Petr Skocik

Reputation: 60058

 cd $yourdir             #go to that dir
 ls -q -p     |             #list all files directly in dir and make directories end with /
 grep '^[0-9]*/$' |      #select directories (end with /) whose names are made of numbers
 sort -n |               #sort numerically
 tail -n1 |              #select the last one (largest)
 xargs -r rmdir          #or rm -r if nonempty 

Recommend running it first without the xargs -r rmdir or xargs -r rm -r part to make sure your deleting the right thing.

Upvotes: 2

gniourf_gniourf
gniourf_gniourf

Reputation: 46823

A pure Bash solution:

#!/bin/bash

shopt -s nullglob extglob

# Make an array of all the dir names that only contain digits
dirs=( +([[:digit:]])/ )

# If none found, exit
if ((${#dirs[@]}==0)); then
    echo >&2 "No dirs found"
    exit
fi

# Loop through all elements of array dirs, saving the greatest number
max=${dirs[0]%/}
for i in "${dirs[@]%/}"; do
    ((10#$max<10#$i)) && max=$i
done

# Finally, delete the dir with largest number found
echo rm -r "$max"

Note:

  • This will have an unpredictable behavior when there are dirs with same number but written differently, e.g., 2 and 0002.
  • Will fail if the numbers overflow Bash's numbers.
  • Doesn't take into account negative numbers and non-integer numbers.
  • Remove the echo in the last line if you're happy with it.
  • To be run from within your directory.

Upvotes: 1

Vytenis Bivainis
Vytenis Bivainis

Reputation: 2376

Let's make some directories to test the script:

mkdir test; cd test; mkdir $(seq 100)

Now

find -mindepth 1 -maxdepth 1 -type d | cut -c 3- | sort -k1n | tail -n 1 | xargs -r echo rm -r

Result:

rm -r 100

Now, remove the word echo from the command and xargs will execute rm -r 100.

Upvotes: 0

Related Questions