Reputation: 131
simple question: I have a variable called x:
echo $x
3122;192.31.231.2 3379;183.3.202.111 3085;218.25.208.92
What I would like is to iterate over the IP's only, not the initial number.
192.31.231.2
183.3.202.111
218.25.208.92
Current code:
for ip in $x;
do
echo `geoiplookup "$ip[$2]"`
done
Upvotes: 2
Views: 141
Reputation: 2884
If we can assume, that between each number and IP address is a semicolon, then we just need to cut until delimiter (i.e. ;
in this case) and select second part.
We can do it in such manner: echo $var | cut -d';' -f2
Now to put this back into your code:
for ip in $x; do
geoiplookup "$(echo $ip | cut -d';' -f2)"
# wrapping it in `echo` would just print what would be printed either way
done
Upvotes: 3
Reputation: 12377
Use this Perl one-liner, connected to a while
loop via a pipe:
perl -lne 'print for /\b\d+;([\d.]+)\b/g' <<<$x | \
while read -r ip ; do
echo "my_command ${ip}"
done
The Perl one-liner uses these command line flags:
-e
: Tells Perl to look for code in-line, instead of in a file.
-n
: Loop over the input one line at a time, assigning it to $_
by default.
-l
: Strip the input line separator ("\n"
on *NIX by default) before executing the code in-line, and append it when printing.
/\b\d+;([\d.]+)\b/g
- Captures and returns IP addresses. Returns multiple matches (regex /g
modifier). Matches \b
- a word boundary, followed by \d+;
- a stretch of digits ending with a semicolon, followed by [\d.]+
- a stretch of digits or periods, followed by \b
- another word boundary.
Upvotes: 1
Reputation: 34946
One idea using parameter expansion:
x="3122;192.31.231.2 3379;183.3.202.111 3085;218.25.208.92"
for stuff in ${x} # process each '<number>;ip' pair separately
do
ip="${stuff##*;}" # strip off leading '<number>;'
echo "${ip}"
# geoiplookup "${ip}"
done
NOTE: I'm not familiar with the geoiplookup
command so not sure why OP is wrapping the geoiplookup
call inside an echo
call versus just calling geoiplookup
directly ... ??
This generates:
192.31.231.2
183.3.202.111
218.25.208.92
From here the OP can reference ${ip}
as needed for the geoiplookup
call.
Upvotes: 3