jasonzx
asked on
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.
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.
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/comman d 10.15.5.50;/path/to/a/diff erent/comm and 142.5.6.188
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/
output:
/path/to/command 10.15.0.1;/path/to/command
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
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;
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Tintin: That works great, it's easy to follow and solves my issue of an unknown amount of IPs at the end.
IP2=awk -F";" '{print $2}' <path-to-file>
IP3=awk -F";" '{print $3}' <path-to-file>