Simple grep Question

I tried searching for answers but didn't find any.

When I grep a file results read

4.2.2.2
4.4.4.2
4.5.6.7

But I just want to select each result individually. For Example I want to be able to say
variable1="first grep result"
variable2="second grep result"
variable3="third grep result"

Thanks in advance.

Hi there,

It would help a lot to analyse Your problem if:
1: You gave an actual sample of the source, ie the "file" content
2. What Your grep or other command sequence looks like right now
3. You give an example of expected output, that is for example, is this variable assignment part of a some script to be used elsewhere?

Otherwise it's only guessing.

/Lakris

head /etc/resolv.conf |grep nameserver| awk '{print $2}'

I get:
68.28.58.92
68.28.50.91

but how can I create two variables
dns1=68.28.58.92
dns2=68.28.50.91

Thanks again.

Hi,

under bash you can try

dns=( $(awk '/nameserver/{print $2}' /etc/resolv.conf ) )

This will give you the second field of all lines matching nameserver read into an array. You can access the data with: echo ${dns[0]}, ${dns[1]} etc.

Kind regards

Chris

Thanks that works but it doesn't like it if the file is empty. I guess I can do my standard grep nameservers | wc -l to check if there is an entry first.

Hi,

keep it simple. A little test is enough:

[[ -s /etc/resolv.conf ]] && dns=( $(awk '/nameserver/{print $2}' /etc/resolv.conf ) )

This means:

if /etc/resolv.conf exists and is not empty, then and only then execute the following command.

Kind regards

Chris

Thanks, looks like it works. Can you explain how this works? I just like to understand it and use it in the future. Also does this work if need to run a command and grab all the output from it....for example running the command /usr/sbin/networksetup -listallnetworkservices on a leopard machine I get all the network services. How would I use this command to only print anyone that contains with "Ethernet".

Since I'm used to using grep I run /usr/sbin/network -listallnetworkservices |grep Ethernet, but I get 3 responses and I need to select each on individually. Can you help?

Thanks again.

Hi elbombillo,

under bash you assign a variable like

var="abba"

and an array is pretty similar

var=( "abba" "acca" adda")

This will give you the array var. You can access the values in var via

echo ${var[0]} ${var[1]} ${var[2]}

$(...) means run the command between the braces and give me the result.
var=( $(...) ) means run the command between the braces and save the result in an array called var. So should be able to capture the output from any command this way.

For an explanation of [[ -s ... ]] see

man test

[[ ... ]] && ... || ...

is a short form of if ... then ... else.

If you have other questions you should open a new post a give an exact description of your problem and your goal.

HTH Chris

Thanks you for taking extra time to explain it.