2014-10-09 72 views
2

我有一個包含子目錄的目錄,其中一些名稱是數字。沒有看,我不知道數字是什麼。我如何刪除號碼最高的子目錄?我認爲解決方案可能會將子目錄按相反順序排序,並選擇以數字開頭的第一個子目錄,但我不知道如何執行此操作。感謝您的幫助。如何刪除具有最高號碼名稱的目錄?

回答

2
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 

建議先運行它沒有xargs -r rmdirxargs -r rm -r部分,以確保您的刪去正確的事情。

+2

我會給你+1,但不要分析'ls':'printf「%s \ n」*/| grep -v'[^ 0-9 /]'|排序......' – 2014-10-09 17:12:51

+0

@glennjackman爲什麼不呢? – PSkocik 2014-10-09 17:23:09

+0

@PSkocik'mkdir $'a \ n10000''。驚喜。 – 2014-10-09 17:52:22

0

讓我們做一些目錄來測試腳本:

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

現在

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

結果:

rm -r 100 

現在,從命令刪除單詞echoxargs將執行rm -r 100

+0

如果只有兩個名爲'a'和'0'的目錄,那麼它將不起作用:OP指定子目錄名的_some_是數字;不是所有的人。 – 2014-10-09 17:58:50

+0

對,'find'缺少參數'-regex「./ [0-9] +」'。 – 2014-10-09 19:21:24

1

純巴什解決方案:

#!/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" 

注:

  • 這將有一個不可預知的行爲時有與相同數量的顯示目錄,但有不同的寫法,例如,20002
  • 如果數字溢出Bash的數字將會失敗。
  • 不考慮負數和非整數。
  • 刪除最後一行中的echo如果您滿意的話。
  • 從您的目錄中運行。
+0

我喜歡它是純粹的bash,但唉,它在第二步中失敗了(在多個匹配的目錄中只找到一個子目錄)。 – PSkocik 2014-10-09 19:59:42

+0

@PSkocik你確定你複製了整個腳本嗎?你能提供一個腳本失敗的例子嗎? – 2014-10-09 20:22:40

+1

我的不好。發生錯誤。嘗試在第二行之後執行echo $ dir,並忘記我需要特殊的「$ {dirs [@]}」來回顯數組。 :)。我的upvote屬於你。 :) – PSkocik 2014-10-09 20:27:26

相關問題