0

been looking for a straight answer to this but not found anything within SO or wider searching that answers this simple question:

I have a string of quoted values, ip addresses in this case, that I want to extract individually to use as values elsewhere. I am intending to do this with sed and regex. The string format is like this:

"10.10.10.101","10.10.10.102","10.10.10.103"

I can capture the values between all quotes using regex such as:

"([^"]*)"

Question is how do I select each group separately so I can use them?

i.e.:

value1 = 10.10.10.101  
value2 = 10.10.10.102  
value3 = 10.10.10.103

I assume that I need three expressions but I cannot find how to select a specific occurance.

Apologies if its obvious but I have spent a while searching and testing with no luck...

3 Answers3

0

Using grep -P you can use match reset:

s="10.10.10.101","10.10.10.102","10.10.10.103"
arr=($(grep -oP '(^|,)"\K[^"]*' <<< "$s"))

# check array content
declare -p arr
declare -a arr='([0]="10.10.10.101" [1]="10.10.10.102" [2]="10.10.10.103")'

If your grep doesn't support -P (PCRE) flag then use:

arr=($(grep -Eo '[.[:digit:]]+' <<< "$s"))

Here is an awk command that should work for BSD awk as well:

awk -F '"(,")?' '{for (i=2; i<NF; i++) print $i}' <<< "$s"
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

If you have GNU awk, you can use FPAT to set the pattern for each field:

awk -v FPAT='[0-9.]+' '{ print $1 }' <<<'"10.10.10.101","10.10.10.102","10.10.10.103"'

Substitute $1 for $2 or $3 to print whichever value you want.

Since your fields don't contain spaces, you could use a similar method to read the values into an array:

read -ra ips < <(awk -v FPAT='[0-9.]+' '{ $1 = $1 }1' <<<'"10.10.10.101","10.10.10.102","10.10.10.103"')

Here, $1 = $1 makes awk reformat each line, so that the fields are printed with spaces in between.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
0

You can try this bash:

$ str="10.10.10.101","10.10.10.102","10.10.10.103"
$ IFS="," arr=($str)
$ echo ${arr[1]}
10.10.10.102 
sat
  • 14,589
  • 7
  • 46
  • 65
  • Many thanks **sat** - this was exactly what I was looking for! Have done similar in the past but for some reason not looked at it this way. – major_slackr May 27 '16 at 14:37