Issue
Sorry if this a basic/stupid question. I have no experience in shell scripting but am keen to learn and develop.
I want to create a script that reads a file, extracts an IP address from one line, extracts a port number from another line and sends them both toa a variable so I can telnet.
My file looks kinda like this;
Server_1_ip=192.168.1.1
Server_2_ip=192.168.1.2
Server_port=7777
I want to get the IP only of server_1 And the port.
What I have now is;
Cat file.txt | while read line; do
my_ip="(grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' <<< "$line")"
echo "$my_ip"
done < file.txt
This works but how do I specify server_1_ip
?
Next I did the same thing to find the port but somehow the port doesn't show, instead it shows "server_port" and not the number behind it
Do i need to cat twice or can I combine the searches? And why does it pass the IP to variable but not the port?
Many thanks in advance for any input.
Solution
Awk may be a better fit:
awk -F"=" '$1=="Server_1_ip"{sip=$2}$1=="Server_port"{sport=$2}END{print sip, sport}' yourfile
This awk says:
- Split each row into columns delimited by an equal sign:
-F"="
- If the first column has the string
"Server_1_ip"
then store the value in the second column to awk variablesip
:$1=="Server_1_ip"{sip=$2}
- If the first column as the string
"Server_port"
then store the value in the second column to awk variablesport
:$1=="Server_port"{sport=$2}
- Once the entire file has been processed, then print out the value in the two variables:
END{print sip, sport}
Answered By - JNevill Answer Checked By - Clifford M. (WPSolving Volunteer)