简体   繁体   中英

How can I delete directories based on their numeric name value with a shell script?

I have a directory that contains numerically named subdirectories ( eg. 1, 2, 3, 32000, 43546 ). I need to delete all directories over a certain number. For example, I need to delete all subdirectories that have a name that is numerically larger than 14234. Can this be done with a single command line action?

rm -r /directory/subdirectories_over_14234 ( how can I do this? )

Well you can do a bash for loop instruction so as to iterate over the directory filename and use the test command then after extracting the target number of the file name.

Should be something like this :

for $file in /your/path 
do
   #extract number here with any text processing command (ed ?)
   if test [$name -leq your_value]
   then
      rm -R $file
   fi
done

In bash, I'd write

for dir in *; do [[ -d $dir ]] && (( dir > 14234 )) && echo rm -r $dir; done

Remove the echo at your discretion.

You don't mention which shell you're using. I'm using Zsh and it has a very cool feature: it can select files based on numbers just like you want! So you can do

$ rm -r /directory/<14234->(/)

to select all the subdirectories of /directory with a numeric value over 14234.

In general, you use

<a-b>

to select paths with a numeric values between a and b . You append a (/) to only match directories . Use (.) to only match files . The glob patterns in Zsh are very powerful and can mostly (if not always) replace the good old find command.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM