python - 使用 IP 在新系列中拆分端口范围
问题描述
嗨,我需要一些帮助,所以我有一个包含以下信息的文件;
IP,Ports,count
"192.168.0.1","80 8980 6789 443 4778 3556 7778 4432 5674 7786 2234 6678 33245 7788 3332 6678 3322 5432 5567",19
"192.168.0.2","80 8980 6789 443 4778 3556 7778 4432 5674 7786 2234 6678 33245 7788 3332 6678 3322 5432 5567",19
"192.168.0.3","80 8980 6789 443 4778 3556 7778 4432 5674 7786 2234 6678 33245 7788 3332 6678 3322 5432 5567",19
"192.168.0.4","80 8980 6789 443 4778 3556 7778 4432 5674 7786 2234 6678 33245 7788 3332 6678 3322 5432 5567",19
我想将端口拆分为 5 个范围,用于具有 IP 的新文件中的每个文件。
预期成绩。
IP,Ports
192.168.0.1 80,8980,6789,443,4778
192.168.0.1 3556,7778,4432,5674,7786
192.168.0.1 2234,6678,33245,7788,3332
192.168.0.1 6678,3322,5432,5067
192.168.0.2 80,8980,6789,443,4778
192.168.0.2 3556,7778,4432,5674,7786
192.168.0.2 2234,6678,33245,7788,3332
192.168.0.2 6678,3322,5432,5067
192.168.0.3 80,8980,6789,443,4778
192.168.0.3 3556,7778,4432,5674,7786
192.168.0.3 2234,6678,33245,7788,3332
192.168.0.3 6678,3322,5432,5067
192.168.0.4 80,8980,6789,443,4778
192.168.0.4 3556,7778,4432,5674,7786
192.168.0.4 2234,6678,33245,7788,3332
192.168.0.4 6678,3322,5432,5067
老实说,我不知道如何做到这一点或从哪里开始。请协助。
无论是在 AWK 还是 python 中都可以,只要向我解释一下脚本/单行代码的作用,以便我可以尝试使用它。
解决方案
您能否尝试以下操作(在显示的示例中测试和编写)。
awk -F'"|","' -v lines=$(wc -l < Input_file) '
BEGIN{
print "IP,ports"
}
FNR>1{
num=split($3,array," ")
for(i=1;i<=num;i++){
if(i==1){ printf $2 OFS }
printf("%s%s",array[i],i%5==0||i==num?ORS:FNR==lines && i==num?ORS:",")
if(i%5==0){ printf $2 OFS }
}
}' Input_file
说明:在此处添加上述的详细说明。
awk -F'"|","' -v lines=$(wc -l < Input_file) ' ##Starting awk program from here.
BEGIN{ ##Starting BEGIN section of this program.
print "IP,ports" ##Printing headers here.
}
FNR>1{ ##Checking condition if current line number is greater than 1st line.
num=split($3,array," ") ##Splitting 3rd field into an array with delimiter space.
for(i=1;i<=num;i++){ ##Traversing through all elements of array here.
if(i==1){ printf $2 OFS } ##if its first element of array then print 2nd field of line and OFS.
printf("%s%s",array[i],i%5==0||i==num?ORS:FNR==lines && i==num?ORS:",") ##Printing array value along with condition if its 5 element or number of total elements equals i then print new line OR current line number equal to lines OR i equals to num then print new line OR print comma.
if(i%5==0){ printf $2 OFS } ##If its 5th element then print current line 2nd field with space
}
}' Input_file ##mentioning Input_file name here.
推荐阅读
- gradle - Creating the fatJar task in doLast in gradle
- python-3.x - Python - Wrapping object with a class and preserving its methods
- javascript - 当一个文本 div 更改时,使其他文本 div 更改大小
- java - 如何使用 log4j 从不同的地方将信息记录到 JTextArea
- c# - 如何在 Windows 窗体 C# 中使用 Binance API
- python - 在图像上绘制相机轴
- php - 将购物车项目发送到电子邮件 PHP
- sqlite - SQLite:如何读取保存为字符串的数组并使用数组?
- firebase - Sidekick Cloud Builds:找不到“Firebase/Core”的规范
- docker - Kubernetes Pod 警告:1 个节点发生卷节点关联冲突