简体   繁体   English

AWK在bash脚本中行为不佳

[英]AWK not behaving in bash Script

When running the ssh line from a command line, it works. 从命令行运行ssh行时,它可以工作。

From a bash script, it appears as: ($ variables inside of awk command are empty) 在bash脚本中,它显示为:(awk命令内的$变量为空)

ssh user@server.example.com netstat --tcp| grep 'servervip3'| grep 'ldap'| awk ' == ESTABLISHED'| awk '{print }'| awk -F: '{print }' >>/somepath/somefile.txt

Script Section: 脚本部分:

    for (( i=0; i<${arraylength}; ++i ))
    do
       # drop all beyond first period in SSH_ADDRESS[i] and add vip3
       host_grep="`echo ${SSH_ADDRESS[i]}|awk -F. '{ print $1 }'`vip3"
         ssh $FIRSTLOGNAME@${SSH_ADDRESS[i]} netstat --tcp| grep '$host_grep'| grep 'ldap'| awk '$6 == "ESTABLISHED"'| awk '{print $5}'| awk -F: '{print $1}' >>$seed_file

done

Any ideas? 有任何想法吗? Thanks -jim 谢谢-jim

Made some minor optimization over your original command as below with a strong dose of awk . 对以下原始命令进行了一些小的优化,并增加了awk剂量。 I have combined 2 grep instances and an awk into one. 我将2个grep实例和一个awk合并为一个。

 ssh $FIRSTLOGNAME@${SSH_ADDRESS[i]} netstat --tcp | awk -v host="$host_grep" '(/host/ || /ldap/) && $6 == "ESTABLISHED" {print $5}' | awk -F: '{print $1}' >>$seed_file

I will explain how this works:- 我将解释这是如何工作的:

  1. Store the hostname to search as an awk variable -v host="$host_grep" so that it will be useful in the regex match. 将主机名存储为awk变量-v host="$host_grep"以便在regex匹配中很有用。
  2. (/host/ || /ldap/) && $6 == "ESTABLISHED" matches any line that has either host as stored in $host_grep or containing the keyword ldap AND having the column six value as "ESTABLISHED" (/host/ || /ldap/) && $6 == "ESTABLISHED"匹配具有host存储在$host_grep或包含关键字ldap并且第6列值为"ESTABLISHED"
  3. awk -F: '{print $1}' delimits your string using : and prints the value before it. awk -F: '{print $1}'使用:分隔字符串,并在其前面打印值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM