在awk中搜索模式

时间:2018-11-20 07:30:08

标签: linux bash shell awk

我想创建一个脚本来检查条件:

  1. 文件中应该包含端口字符串,如果是,则其值为20000。

  2. 文件中应提及sslkey,sslCert,ssl_cipher(这些字符串/键的值可以是任何值)。

已尝试:

$ awk '/port|sslKey|sslCert|ssl_cipher/ {print $2,$3}' pkg.conf
port 20000
sslKey /usr/product/plat/etc/ssl/server.pem
sslCert /usr/product/plat/etc/ssl/server.cert
ssl_cipher ECDH+AES128:ECDH+AESGCM:ECDH+AES256:DH+AES:DH+AESGCM:DH+AES256:RSA+AES:RSA+AESGCM:!aNULL:!RC4:!MD5:!DSS:!3DES

上述命令的问题是,即使丢失了字符串'port | sslKey | sslCert | ssl_cipher'之一,它仍然可以运行。

可以仅使用几行awk来实现。

如果缺少任何字符串/条件,则输出应显示该条件以及满足的条件。

1 个答案:

答案 0 :(得分:0)

考虑到您在问题中的详细信息,请参见输入示例:

正确:

$ cat pkg.conf
port 20000
sslKey /usr/product/plat/etc/ssl/server.pem
sslCert /usr/product/plat/etc/ssl/server.cert
ssl_cipher ECDH+AES128:ECDH+AESGCM:ECDH+AES256:DH+AES:DH+AESGCM:DH+AES256:RSA+AES:RSA+AESGCM:!aNULL:!RC4:!MD5:!DSS:!3DES

错误(端口18000和缺少sslCert):

$ cat pkg_wrong.conf
port 18000
sslKey /usr/product/plat/etc/ssl/server.pem
ssl_cipher ECDH+AES128:ECDH+AESGCM:ECDH+AES256:DH+AES:DH+AESGCM:DH+AES256:RSA+AES:RSA+AESGCM:!aNULL:!RC4:!MD5:!DSS:!3DES

AWK解决方案:

更正pkg.conf。返回0,不输出任何内容:

$ awk '
/^port [0-9]+$/ { if ( $2 == 20000 ) isport=1; port=$2; }
/^sslKey .+$/ { issslKey=1; sslKey=$2; }
/^sslCert .+$/ { issslCert=1; sslCert=$2; }
/^ssl_cipher .+$/ { isssl_cipher=1; ssl_cipher=$2; }
END { if (isport && issslKey && issslCert && isssl_cipher) exit(0);
      else { print("port " port); print("sslKey " sslKey); print("sslCert " sslCert); print("ssl_cipher " ssl_cipher); exit(1); }
    }
' pkg.conf

pkg_wrong.conf错误(端口18000,缺少sslCert):

$ awk '
/^port [0-9]+$/ { if ( $2 == 20000 ) isport=1; port=$2; }
/^sslKey .+$/ { issslKey=1; sslKey=$2; }
/^sslCert .+$/ { issslCert=1; sslCert=$2; }
/^ssl_cipher .+$/ { isssl_cipher=1; ssl_cipher=$2; }
END { if (isport && issslKey && issslCert && isssl_cipher) exit(0);
      else { print("port " port); print("sslKey " sslKey); print("sslCert " sslCert); print("ssl_cipher " ssl_cipher); exit(1); }
    }
' pkg_wrong.conf
port 18000
sslKey /usr/product/plat/etc/ssl/server.pem
sslCert
ssl_cipher ECDH+AES128:ECDH+AESGCM:ECDH+AES256:DH+AES:DH+AESGCM:DH+AES256:RSA+AES:RSA+AESGCM:!aNULL:!RC4:!MD5:!DSS:!3DES