How do I real from a file and split into variables in BASH?

I have a file with lines in the following format:
10.15.0.1; 10.15.1.27; 10.15.5.50; 142.5.6.188, 142.9.88.122

There is always going to be 3 IP addresses separated by semi-colons, then one or more IP addresses separated by commas.
I need to process the file and run several commands using the first three IP addresses, then run a several commands on each of the comma-separated IPs.

I tried using IFS and nested for loops but didn't know how to pull off the second loop.
jasonzxAsked:
Who is Participating?
 
TintinConnect With a Mentor Commented:
i think this is the easiest approach
#!/bin/bash
sed "s/[;,]//g" file|while read ip1 ip2 ip3 ips
do
  echo "ip1=$ip1"
  echo "ip2=$ip2"
  echo "ip3=$ip3"

  for ip in $ips
  do
    echo "IP=$ip"
  done
done

Open in new window

0
 
wesly_chenCommented:
IP1=awk -F";" '{print $1}' <path-to-file>
IP2=awk -F";" '{print $2}' <path-to-file>
IP3=awk -F";" '{print $3}' <path-to-file>
0
 
chenry334Commented:
You can use awk to parse the string... just use multiple field separators - ie:

input:
chenry@home:~$ echo "10.15.0.1; 10.15.1.27; 10.15.5.50; 142.5.6.188, 142.9.88.122" | awk 'BEGIN { FS = "[;,]"} ; {print "/path/to/command "$1";/path/to/command "$2";/path/to/command "$3";/path/to/a/different/command"$4}'

output:
/path/to/command 10.15.0.1;/path/to/command  10.15.1.27;/path/to/command  10.15.5.50;/path/to/a/different/command 142.5.6.188
0
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

 
farzanjCommented:
Try this:
#!/bin/bash

FILE='file.txt'
cat $FILE | while read line
do
IP1=$(awk -F';' '{print $1}')
IP2=$(awk -F';' '{print $2}')
IP3=$(awk -F';' '{print $3}')
IP4=$(awk -F';' '{print $4}' | awk -F',' '{print $1}')
IP5=$(awk -F';' '{print $4}' | awk -F',' '{print $2}')
echo $IP1

#NOW DO YOUR PROCESSING
done

Open in new window

0
 
farzanjCommented:
If you are open to use perl you can do something like this
#!/usr/bin/perl


my $File = 'filename';

open (IN, $FILE) or die "Could not open the file $!";
my @lines = <IN>;
close IN;

foreach my $line (@lines)
{
   $line =~ m/([\d.]+); ([\d.]+); ([\d.]+); ([\d.]+), ([\d.]+)/;
   #These lines are just to show you where the values are
   #You can start using them now
   my $IP1 = $1;
   my $IP2 = $2;
   my $IP3 = $3;
   my $IP4 = $4;
   my $IP5 = $5;
}

Open in new window

0
 
jasonzxAuthor Commented:
Tintin: That works great, it's easy to follow and solves my issue of an unknown amount of IPs at the end.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.