Bash: convert '\ n' separable strings to array

I have this script -

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

now the $names variable contains strings separated by newlines -

 >_ (Netgear) (Hon Hai Precision Ind. Co.) (Apple) 

I tried to do array conversion with subscript approach -

 names=(${names//\\n/ }) echo "${names[@]}" 

But the problem is that I cannot access them by indexing (ie ${names[$i] etc.) if I run this loop -

 for (( i=0; i<${#names[@]}; i++ )) do echo "$i: ${names[$i]" # do some processing with ${names[$i]} done 

I get this conclusion -

 >_ 0: (Netgear) 1: (Hon 2: Hai 

but I want -

 >_ 0: (Netgear) 1: (Hon Hai Precision Ind. Co.) 2: (Apple) 

I could not figure out how to do this, please note that there are spaces in the second line.

Any idea?

+17
arrays bash newline
source share
3 answers

Install IFS . The shell uses the IFS variable to define field separators. By default, IFS set to a space. Change this to a new line.

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

Exit

 0: Netgear 1: Hon Hai Precision Ind. Co. 2: Apple 
+23
source share

Let me contribute to Sanket Parmar's answer . If you can extract the separation and processing of strings 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:

+9
source share

As others have said, IFS will help you. IFS=$'\n' read -ra array <<< "$names" if your variable has a string with spaces, put it in double quotes. Now you can easily get all the values ​​in an array with ${array[@]}

+1
source share

All Articles