saee
saee

Reputation: 9

How do I write a shell script to fetch a value from key:value pair in the text file?

I have a text file for example

server_ip: 1.1.1.1
server_port: 123

How do I write a linux shell script that would give me the value based on the server_ip key.

Sample File

[LOGGER]
server_ip: 1.1.1.1
server_port:123
#many such blocks as shown above

Upvotes: 0

Views: 2576

Answers (2)

John1024
John1024

Reputation: 113834

Answers for original question

Using awk:

$ awk '/^server_ip/ {print $2}' file
1.1.1.1

This selects any line that begins with server_ip and prints the second field on that line.

Using sed:

$ sed -n 's/server_ip: //p' file
1.1.1.1

This attempts to remove server_ip: from a line and only prints output for those lines for which the substitution succeeds.

Using grep -P (requires GNU grep):

$ grep -oP '(?<=server_ip: ).*' file
1.1.1.1

This uses a Perl-style look-behind to select text which follows server_ip:.

Answers for revised question

Let's consider this test file:

$ cat file
[GOG]
server_ip: 2.2.2.2
server_port: 123
[LOGGER]
server_ip: 1.1.1.1
server_port: 123
[FOG]
server_ip: 3.3.3.3
server_port: 123

Using awk:

$ awk '/LOGGER/,/^server_ip/{if (/^server_ip/) print $2}' file
1.1.1.1

Using sed:

$ sed -n '/LOGGER/,/^server_ip/{s/server_ip: //p}' file
1.1.1.1

Assigning output to a variable

Output that appears on stdout on the screen can be captured to a variable using command substitution which looks like $(...). Thus:

ip="$(awk '/^server_ip/ {print $2}' file)"

Or:

ip="$(sed -n 's/server_ip: //p' file)"

Or:

ip="$(grep -oP '(?<=server_ip: ).*' file)"

Upvotes: 2

sjsam
sjsam

Reputation: 21965

Your question is not immensely clear. If you were looking for the port based on the ip, you would have used a small script for the purpose. Input

$ cat file
[GOG]
server_ip: 2.2.2.2
server_port: 123
[LOGGER]
server_ip: 1.1.1.1
server_port: 123
[FOG]
server_ip: 3.3.3.3
server_port: 123

Script

#!/bin/bash
if [ -z "$1" ]
then
echo "Usage : command server_name"
exit 1
fi
sed -n "/$1/{n;N;p;q}" file

On Running

$ ./script LOGGER
server_ip: 1.1.1.1
server_port: 123

Upvotes: -1

Related Questions