AndyM
AndyM

Reputation: 622

Bash find string postion in list of strings

Whats the best way to achieve the following?

I want my script to find out which postion the host its running on is in a list of hosts.

thisHost=$(hostname)

machineList="pc02 server03 host01 server05"

So if thisHost=host01 I would get back postion 3.

The machine list would never be contain more than 10 items.

I could do a comparison match in a for loop but would like to know if there is a better way ?

Upvotes: 1

Views: 247

Answers (4)

Fritz G. Mehner
Fritz G. Mehner

Reputation: 17198

(1) An inexpensive one-liner:

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

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

Substitute the rest of the list beginning with $host with dummy and count the words with wc.

(2) Pure Bash:

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

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

Shorten the list as shown above and return the number of elements of the array shortList.

The output is 3 in both solutions.

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92904

Awk one-line solution:

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

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

The output:

3

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92904

Bash solution:

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

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

The output:

position: 3

Upvotes: 1

choroba
choroba

Reputation: 242423

If you need to check many hosts, you can prepare a better structure for faster lookup: an associative array:

#! /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]}

You can also use external tools:

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

Upvotes: 4

Related Questions