以我们想要的方式输出文件

时间:2015-09-08 13:47:44

标签: bash shell

我有ssh配置文件,其中包含来自google,aws和一些远程服务器的很多服务器。我想要一个bash函数,它只输出服务器的Host和HostName,所以我不必记住那里的公共DNS检查我的webapps。

我的ssh配置中的示例服务器配置如下所示

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

我希望输出像

aws_server                 65.2.25.152

适用于所有服务器

3 个答案:

答案 0 :(得分:5)

使用sed

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

aws_server      65.2.25.152

修改后的版本对多个主机更加健壮,缺少HostNames

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

答案 1 :(得分:2)

使用awk

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

答案 2 :(得分:1)

我会使用awk

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
相关问题