linux 中删除除第一次匹配特定字符串所在行之外的所有行
2022/8/4 5:24:01
本文主要是介绍linux 中删除除第一次匹配特定字符串所在行之外的所有行,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
001、shell实现
root@PC1:/home/test2# ls test.txt root@PC1:/home/test2# cat test.txt ## 测试数据, 删除第一次匹配xpehh以外的所有匹配xpehh的行 01 ee ff 02 ee de 03 dd ee 04 jj xpehh 05 jj kk 06 ee de 07 mm xpehh 08 ff ww 09 jj kk 10 mm xpehh 11 dd ee root@PC1:/home/test2# awk 'BEGIN{idx = 0} {if($0 ~ /xpehh/ && idx == 0 || $0 !~ /xpehh/) {print $0}; if($0 ~ /xpehh/) {idx++}}' test.txt 01 ee ff 02 ee de 03 dd ee 04 jj xpehh 05 jj kk 06 ee de 08 ff ww 09 jj kk 11 dd ee
002、python实现
root@PC1:/home/test2# ls test.py test.txt root@PC1:/home/test2# cat test.txt 01 ee ff 02 ee de 03 dd ee 04 jj xpehh 05 jj kk 06 ee de 07 mm xpehh 08 ff ww 09 jj kk 10 mm xpehh 11 dd ee root@PC1:/home/test2# cat test.py #!/usr/bin/python in_file = open("test.txt", "r") out_file = open("result.txt", "w") lines = in_file.readlines() idx = 0 for i in lines: if idx == 0 and "xpehh" in i or "xpehh" not in i: out_file.write(i) if "xpehh" in i: idx = idx + 1 in_file.close() out_file.close() root@PC1:/home/test2# python test.py root@PC1:/home/test2# ls result.txt test.py test.txt root@PC1:/home/test2# cat result.txt ## 结果文件 01 ee ff 02 ee de 03 dd ee 04 jj xpehh 05 jj kk 06 ee de 08 ff ww 09 jj kk 11 dd ee
003、R实现
dir() dat <- read.table("test.txt") result <- vector() idx = 0 for (i in 1:nrow(dat)) { if (sum(grepl("xpehh", dat[i,])) != 0 & idx == 0 | sum(grepl("xpehh", dat[i,])) == 0) { result <- c(result, i) } if(sum(grepl("xpehh", dat[i,])) != 0){ idx = idx + 1 } } final <- dat[result,] final
这篇关于linux 中删除除第一次匹配特定字符串所在行之外的所有行的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-08-15个人linux下开发常用命令
- 2022-08-15Linux查看当前Cuda(CUDA Toolkit )版本
- 2022-08-15在Linux安装ElasticSearch
- 2022-08-15linux如何用top查看cpu占用率大于1的?
- 2022-08-15Linux网络命令总结
- 2022-08-15Linux免密登陆
- 2022-08-15如何在Linux中按内存和CPU使用率查找运行次数最多的进程
- 2022-08-15用10行shell脚本监控Linux
- 2022-08-15关于linux的一点好奇心(四):tail -f文件跟踪实现
- 2022-08-14Linux系列之链接