2017-12-12 1 views
1

다음을 달성하는 가장 좋은 방법은 무엇입니까?Bash는 문자열 목록에서 문자열 위치를 찾습니다.

내 스크립트에서 호스트가 실행중인 호스트가 호스트 목록에 있는지 알아야합니다.

thisHost=$(hostname) 

machineList="pc02 server03 host01 server05" 

그래서 thisHost=host01 경우 나는 위치보다 3

10 개 이상의 항목을 포함하지 않을 것이다 기계 목록 돌아갈 것입니다.

for 루프에서 비교 일치를 수행 할 수 있지만 더 좋은 방법이 있는지 알고 싶습니다. 당신이 많은 호스트를 확인해야하는 경우

답변

1

Bash을 솔루션 :

thisHost="host01" 
machineList="pc02 server03 host01 server05" 
machineListArr=($machineList) 

for i in "${!machineListArr[@]}"; do 
    [ "$thisHost" = "${machineListArr[$i]}" ] && echo "position: $((i+1))" 
done 

의 출력 :

position: 3 
4

, 당신은 빠른 조회를위한 더 나은 구조를 준비 할 수 있습니다 : 연관 배열 :

#! /bin/bash 
machineList='pc02 server03 host01 server05' 
declare -A machine_number 
i=1 
for machine in $machineList ; do 
    machine_number[$machine]=$((i++)) 
done 

thisHost=host01 
echo ${machine_number[$thisHost]} 

또한 사용할 수있는 외부 도구 :

read n _rest < <(echo "$machineList" 
       | tr ' ' '\n' 
       | nl 
       | grep -Fw "$thisHost") 
echo $n 
+0

감사합니다. 목록이 10 대 정도의 기계 일 것이라고 말하는 질문을 편집했습니다. – AndyM

1

Awk한줄 용액 :

thisHost="host01" 
machineList="pc02 server03 host01 server05" 

awk -v RS=" " -v h="$thisHost" '$0==h{ print NR }' <<<"$machineList" 

출력 :

3 
1

(1)는 저렴 하나 라이너

host='host01' 
    machineList="pc02 server03 host01 server05" 

    wc -w <<< ${machineList/%${host}*/dummy} 

$host으로 시작하는 나머지 목록을 dummy으로 대체하고 wc으로 단어를 센다.

(2) 순수 배시 :

host='host01' 
    machineList="pc02 server03 host01 server05" 

    shortList=(${machineList/%${host}*/dummy}) 
    echo ${#shortList[@]} 

위에서 도시 된 바와 같이리스트를 단축하고 shortList 배열의 요소의 수를 반환한다.

두 솔루션 모두 출력이 3입니다.

관련 문제