2012-08-13 87 views
2

串我有命名的文件夾:擊:更換空字符串

example1 example2 example3 

我想從他們每個人提取的例子數。例如:

for exampleSubfolder in `find . -type d` 
do 
    example_number= #replace 'example' in $exampleSubfolder with empty string 
    #do other stuff in this subfolder 
done 

任何簡單的方法來做到這一點?

+1

如果您的文件夾是在當前目錄中,'爲exampleSubfolder例如/'避免了'find'調用。 – tripleee 2012-08-13 10:01:26

回答

4

如果你只需要數量:

find . -type d -name 'example*' | egrep -o "[0-9]+" 

但是,如果你想知道文件夾名稱和編號之間的對應關係:

for f in $(find . -mindepth 1 -maxdepth 1 -type d -name 'example*') 
do 
    number=${f#example} 
done 

與字符串替換更新bashism。

+0

不錯,所以我可以做'echo $ exampleSubfolder | egrep -o「[0-9] +」'得到的數字爲 – 2012-08-13 09:51:55

+0

它將緩衝到儘可能深的程度,而不是隻有一個級別,並且使用bash glob的效率會降低,並且它會匹配任何位置的路徑上的數字,而不只是在最後。 – Geoffrey 2012-08-13 09:55:39

+0

你可以通過'number = $ {f#example}'來避免外部過程。 – tripleee 2012-08-13 10:00:36

2

試試這個:

for DIR in /path/to/search/example*; do 
    if [ ! -d $DIR ]; then continue; fi 
    NUMBER=$(echo $DIR | grep -Eo '[0-9]+$') 
    pushd $DIR 
    # Do stuff here 
    popd 
done 
2
find . -name "example*" -type d | awk -F"example" '{print $NF}'