我需要驗證文件中的IP範圍並進行更正。使用bash驗證IP範圍
文件有這些不好的範圍:
192.168.1.2-192.168.1.1
10.0.0.10-10.0.0.8
172.16.0.9-172.16.0.5
的問題是,結束地址可起始地址前,還沒來的及,應更正爲:
192.168.1.1-192.168.1.2
10.0.0.8-10.0.0.10
172.16.0.5-172.16.0.9
我的文件有很多,這些壞的範圍,所以自動校正方式會很好。
我需要驗證文件中的IP範圍並進行更正。使用bash驗證IP範圍
文件有這些不好的範圍:
192.168.1.2-192.168.1.1
10.0.0.10-10.0.0.8
172.16.0.9-172.16.0.5
的問題是,結束地址可起始地址前,還沒來的及,應更正爲:
192.168.1.1-192.168.1.2
10.0.0.8-10.0.0.10
172.16.0.5-172.16.0.9
我的文件有很多,這些壞的範圍,所以自動校正方式會很好。
海蘭,
你必須執行以下步驟:
以下腳本不會他:
#!/bin/bash
filename="$1"
#Step1: read each line from file
#see http://stackoverflow.com/questions/10929453/bash-scripting-read-file-line-by-line
while read -r line
do
#Step2: split each line in ips
#see http://stackoverflow.com/questions/10586153/split-string-into-an-array-in-bash
IFS='-' read -r -a array <<< "$line"
#Step3: sort the ips
#see http://stackoverflow.com/questions/7442417/how-to-sort-an-array-in-bash
#for sorting ips see: https://www.madboa.com/geek/sort-addr/
IFS=$'\n' sorted=($(sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4 <<<"${array[*]}"))
unset IFS
#Step4: echo the results
echo ${sorted[0]}"-"${sorted[1]}
done < "$filename"
下列文件中的結果:
192.168.1.2-192.168.1.1
10.0.0.10-10.0.0.8
172.16.0.5-172.16.0.9
是:
192.168.1.1-192.168.1.2
10.0.0.8-10.0.0.10
172.16.0.5-172.16.0.9
它幾乎按預期工作。但是,當在產品列表中進行測試時,結束範圍會轉到新行https://gist.github.com/Demontager/c4d04c927d338d592f98 ps.s.適用於我的樣品。 – Demontager
@Demontager:如果它「能找到我的樣本」,那麼你應該通過http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235接受提供的答案。 。如果您沒有正確指定您的問題,那麼您應該通過編輯您的Q來要求澄清,而不是提供一個指向非現場數據集的鏈接。祝你好運。 – shellter
@shellter,接受。 – Demontager
鑑於你的樣品輸入/輸出,那麼所有你需要的是這樣的,使用GNU AWK的gensub ():
$ awk -F- {print (gensub(/.*\./,"",1,$1) < gensub(/.*\./,"",1,$2) ? $1 FS $2 : $2 FS $1)}' file
192.168.1.1-192.168.1.2
10.0.0.10-10.0.0.8
172.16.0.5-172.16.0.9
With ot她的沙發只是使用了幾個本地變量和sub()。
但是,如果你需要的作品,當IP addrs的不僅僅是最後一節的其他部分可以在一個給定的線不同的解決方案(例如172.16.0.5-172.15.0.9
),那麼這將在任何AWK工作:
$ cat tst.awk
BEGIN { FS="-" }
{
split($1,t,/\./)
beg = sprintf("%03d%03d%03d%03d", t[1], t[2], t[3], t[4])
split($2,t,/\./)
end = sprintf("%03d%03d%03d%03d", t[1], t[2], t[3], t[4])
print (beg < end ? $1 FS $2 : $2 FS $1)
}
$ awk -f tst.awk file
192.168.1.1-192.168.1.2
10.0.0.8-10.0.0.10
172.16.0.5-172.16.0.9
$ echo '172.16.0.5-172.15.0.9' | awk -f tst.awk
172.15.0.9-172.16.0.5
如果您正在考慮使用shell循環來操作文本,請確保您先閱讀並完全理解https://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice。
你爲什麼要「倒置」最後一個記錄? –
,因爲當我嘗試使用masscan它會報告錯誤,並且無法正常工作。 $ masscan -iL range.txt -oL res.txt -p 80 err:結束addr 10.0.0.8在啓動addr之前不能來255.255.255.255不好範圍spec:「10.0.0.10-10.0.0.8」 – Demontager
我認爲問題是爲什麼在第三個例子中'172.16.0.9'被認爲是* 172.16.0.5之前的*。 –