Convert multiline string to array

后端 未结 4 1576

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 01:43

    Bash also has a readarray builtin command, easily searchable in the man page. It uses newline (\n) as the default delimiter, and MAPFILE as the default array, so one can do just like so:

        names="Netgear
        Hon Hai Precision Ind. Co.
        Apple"
    
        readarray -t <<<$names
    
        printf "0: ${MAPFILE[0]}\n1: ${MAPFILE[1]}\n2: ${MAPFILE[2]}\n"
    

    The -t option removes the delimiter ('\n'), so that it can be explicitly added in printf. The output is:

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

提交回复
热议问题