Reputation: 1
I am trying to grab the Word from a text file AFTER the IP regex match ($2):
fileName.txt:
IP hostname blah blah blah...
blah blah..
IP hostname blah blah blah... . . .
I want the hostnames for each instance of the IP (which I found with grep regex and stored it in $var). I want to use found hostnames to set to $host and print them out onto a text file with the IPs (which are already done).
I have tried multiple methods from online answers but they all printed blanks.
Thank you!
Upvotes: 0
Views: 123
Reputation: 67467
awk
to the rescue!
$ awk '/^([0-9]{1,3}\.){3}[0-9]{1,3}/{print $1, $2}'
will give you IP hostname for the lines starting with the matching regex.
if your awk doesn't support regex interval you need the add --re-interval option.
Upvotes: 0
Reputation: 295278
See BashFAQ #1 for guidance on how best to read from a stream.
#!/bin/bash
# ^^^^ important, not /bin/sh
while read -r -a words; do
# put the array words into $1, $2, $3, etc.
set -- "${words[@]}"
# put $1 -- the first word -- into the variable named "ip"
ip=$1
# remove $1, leaving only hostnames in $1, $2, etc
shift
echo "IP address $ip has the following hostnames:"
for hostname; do # by default, a for loop iterates over $@
echo "- ${hostname}"
done
done < <(grep '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' test_amy_hostrun.txt)
Upvotes: 1