选择除一块文本之外的所有内容

时间:2016-11-14 20:31:15

标签: bash ubuntu awk sed grep

我有一个用于分布式网络监控系统的综合主机文件,我需要将其拆分为两个文件。一些主机进入一个文件,其余主机进入另一个文件。我使用sed来拉出我需要的主机,但我不知道如何将其他所有内容放在另一个文件中,有点像{{1} -v选项}}

主机文件示例:

grep

我用来拉出路由器的object Host "router" { import "template" display_name = "router" address = "xx.xx.xx.xx " } object Host "switch" { import "template" display_name = "switch" address = "xx.xx.xx.xx " } object Host "router" { import "template" display_name = "router" address = "xx.xx.xx.xx " } object Host "otherthing" { import "template" display_name = "otherthing" address = "xx.xx.xx.xx " } object Host "switch" { import "template" display_name = "switch" address = "xx.xx.xx.xx " } object Host "otherthing" { import "template" display_name = "otherthing" address = "xx.xx.xx.xx " } 命令

sed

此外,我不知道排序是否更有效,而不是构建大型主机文件,但这是我如何制作大型主机文件:

sed '/router.*\n/p;//g;/{$/,/^}/H;//x;D' files/tmp/unsorted-host.tmp >> files/router.conf

目标是拥有两个文件,一个包含路由器,另一个包含其他所有文件。提前感谢任何建议!

2 个答案:

答案 0 :(得分:2)

使用awk:

awk -v RS= '/router/' hosts.txt > routers.txt
awk -v RS= '!/router/' hosts.txt > non_routers.txt

或有一个awk:

awk -v RS= '/router/ {print > "routers.txt"}; !/router/ {print > "non_routers.txt"}' hosts.txt

请参阅:8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR

答案 1 :(得分:1)

这不是答案:我发现大嵌套if很痛苦。快速重写:

while read -r ip rest_of_line; do
    # The SNMP to check the device type outputs on multiple lines, check to ensure we only grab IP's
    ping -c 1 "$ip" &> /dev/null || continue
    template="template"
    host_name=
    for n in 1 2 3 4 5; do
        host_name=$(timeout -s KILL 2 /usr/bin/snmpwalk -v 2c -c community$n "$ip" 1.3.6.1.2.1.1.5.0 | awk '{print $NF}')
        [ -n "$host_name" ] && break
    done
    if [ -z "$host_name" ]; then 
        echo "host not found for ip $ip" >&2
        continue
    fi
    echo "
object Host $host_name {
  import \"$template\"
  display_name = $host_name
  address = \"$ip \"
}" 
done < files/tmp/hosts.tmp > files/tmp/unsorted-hosts.tmp