Convert multiline string to array

后端 未结 4 1569

I have this script:

nmapout=`sudo nmap -sP 10.0.0.0/24`
names=`echo "$nmapout" | grep "MAC" | grep -o \'(.\\+)\'`
echo "$names"
         


        
4条回答
  •  旧巷少年郎
    2020-12-14 02:06

    Set IFS. Shell uses IFS variable to determine what the field separators are. By default IFS is set to the space character. Change it to newline.

    #!/bin/bash
    names="Netgear
    Hon Hai Precision Ind. Co.
    Apple"
    
    SAVEIFS=$IFS   # Save current IFS
    IFS=$'\n'      # Change IFS to new line
    names=($names) # split to array $names
    IFS=$SAVEIFS   # Restore IFS
    
    for (( i=0; i<${#names[@]}; i++ ))
    do
        echo "$i: ${names[$i]}"
    done
    

    Output

    0: Netgear
    1: Hon Hai Precision Ind. Co.
    2: Apple
    

提交回复
热议问题