Home > other >  Shell script breaks with grep
Shell script breaks with grep

Time:03-18

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.

CodePudding user response:

You could do something like:

#!/bin/bash

while IFS='=' read key value; do
        case "$key" in
        Server_1_ip) target_ip="$value";;
        Server_port) target_port="$value";;
        esac
done < input

This is almost certainly not the appropriate solution, since it requires you to statically define the string Server_1_ip, but it's not entirely clear what you are trying to do. You could eval the lines, but that is risky.

How exactly you want to determine the host name to match will greatly influence the desired solution. Perhaps you just want something like:

#!/bin/bash

target_host="${1-Server_1_ip}"
while IFS='=' read key value; do
        case "$key" in
        $target_host) target_ip="$value";;
        Server_port) target_port="$value";;
        esac
done < input

CodePudding user response:

Awk may be a better fit:

awk -F"=" '$1=="Server_1_ip"{sip=$2}$1=="Server_port"{sport=$2}END{print sip, sport}' yourfile

CodePudding user response:

Here's a sed variant:

sed -n -e'/Server_1_ip=\(.*\)/{s//\1/;h}; /Server_port=\([0-9]*\)/{s// \1/;H;g;s/\n//p;q}' inputfile
  • -n stops normal output,
  • apply -e commands
    • First find target server, ie. Server_1_ip= with a subexpression that remembers the value (assumed its well formed IPv4). Apply a command block that replaces the pattern space (aka current line) with the saved subexpression and then copies the pattern space to the hold buffer; end command block.
    • Continue looking for port line. Apply command block that removes the prefix leaving the port number; append the port to the hold buffer (so now you have IP newline port in hold); copy the hold buffer back to pattern space; delete the newline and print result; quit.

Note: GNU and BSD sed can vary especially with trying to join lines, ie. s/\n//.

  • Related