5ud0
5ud0

Reputation: 119

Output the file in way we wanted

I have ssh config file which contains so many servers from google,aws and some remote servers.I wanted to have a bash function that will output only the Host and the HostName of the server so I dont have to remember there public DNS to check my webapps.

Sample Server Config in my ssh config looks like this

Host aws_server
        User                    rand
        HostName                65.2.25.152
        Port                    8000
        IdentityFile            PEM PATH
        ServerAliveInterval     120
        ServerAliveCountMax     30

I want the output like

aws_server                 65.2.25.152

for all the servers

Upvotes: 0

Views: 59

Answers (3)

123
123

Reputation: 11216

Using sed

sed '/^Host/{s/[^ ]* //;:1;N;s/\n.*HostName */\t/;t2;b1;:2;p};d' file

aws_server      65.2.25.152

Modified version that's more robust for multiple hosts,missing HostNames

sed ':1;s/\(.*\n\|^\)Host *//;N;s/\n.*HostName */\t/;t2;$!{b1;:2;p};d' file

Upvotes: 5

Shravan Yadav
Shravan Yadav

Reputation: 1317

using awk

awk '{if($1=="Host")k=$2;if($1=="HostName")printf("%s\t%s\n",k,$2)}' file

Upvotes: 2

Etan Reisner
Etan Reisner

Reputation: 80961

I would use awk for this:

awk '
    # Save the host when we see it.
    /^Host/ {
        host=$2
        next
    }
    # If we have a host and are on a HostName line
    host && $1 == "HostName" {
        # Print the Host and HostName values
        printf "%s"OFS"%s\n", host, $2
        host=""
        next
    }
    # If we have a HostName without a Host clear the host (should not happen but just to be safe)
    $1 == "HostName" {
        host=""
    }
' .ssh/config

Upvotes: 1

Related Questions