[英]Using Bash to search files for
我有兩個文本文件,一個具有唯一的 IP 地址列表,另一個具有更長的 IP 地址填充列表。 我正在嘗試使用 bash 確定唯一列表中的哪些 IP 地址出現在較長的人口列表中。
到目前為止,我有:
#!/bin/bash
while read line; do
grep -Ff "$line" population.txt
done < $uniqueIP.txt
腳本運行,但我沒有得到 output。 我正在嘗試計算出現次數,但在邏輯上遇到問題。 目前,該腳本沒有 output 任何東西。
樣本輸入:
唯一IP.txt
192.168.1.10
192.168.1.11
192.168.1.12
192.168.1.13
192.168.1.14
人口.txt
192.168.1.12
192.168.1.14
192.168.1.15
192.168.1.16
192.168.1.17
192.168.1.18
192.168.1.19
192.168.1.22
192.168.1.23
樣品 Output:
Found: 192.168.1.12
Found: 192.168.1.14
Total: 2
這是我為您的問題建議的 bash function count_unique_ips
#!/bin/bash
function count_unique_ips()
{
local unique_ips_file=$1
local population_file=$2
local unique_ip_list=$(tr ' ' '\n' < ${unique_ips_file} | sort | uniq)
for ip in "${unique_ip_list[@]}"; do
count=$(grep -o -i ${ip} ${population_file} | wc -l)
echo "'${ip}': ${count}"
done
}
count_unique_ips uniqueIP.txt population.txt
您應該根據 2 個給定的輸入文件uniqueIP.txt
和population.txt
獲得以下 output
'192.168.1.10': 0
'192.168.1.11': 0
'192.168.1.12': 1
'192.168.1.13': 0
'192.168.1.14': 1
一個簡短的方法,只使用grep
,可以是
grep -Fxf uniqueIP.txt population.txt
但這對於大文件來說會很慢。 更快的方法是
sort uniqueIP.txt population.txt | uniq -d
假設 population.txt 中的 IP 在此文件中也是唯一的,並且每行一個 IP 沒有額外字符(包括空白字符)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.