Convert multiline string to array

后端 未结 4 1565

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:04

    Let me contribute to Sanket Parmar's answer. If you can extract string splitting and processing into a separate function, there is no need to save and restore $IFS — use local instead:

    #!/bin/bash
    
    function print_with_line_numbers {
        local IFS=$'\n'
        local lines=($1)
        local i
        for (( i=0; i<${#lines[@]}; i++ )) ; do
            echo "$i: ${lines[$i]}"
        done
    }
    
    names="Netgear
    Hon Hai Precision Ind. Co.
    Apple"
    
    print_with_line_numbers "$names"
    

    See also:

    • Setting IFS for a single statement

提交回复
热议问题