2012-08-13 2 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 

간단한 방법이 있나요?

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

하지만 당신은 폴더 이름과 번호 사이의 correspondance에를 알고 싶다면 : : 문자열로 업데이트

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

이 bashism를 교체 할 경우에만 번호가 필요하면

+1

를 폴더는 현재 디렉토리에있는 경우 '예 exampleSubfolder에 대한 /'은'find' 호출은 피할 수 있습니다. – tripleee

답변

4

.

+0

니스, 그래서 할 수있는'echo $ exampleSubfolder | egrep -o "[0-9] +"'그리고 숫자 –

+0

을 얻을 수 있습니다. 단지 하나의 레벨 대신에 가능한 한 반복적으로 재귀 적으로 실행될 것이고, 배시 글로브를 사용하면 덜 효율적입니다. , 단지 끝이 아니다. – Geoffrey

+0

'number = $ {f # example}'하면 외부 프로세스를 피할 수 있습니다. – tripleee

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}'