c++ - 如何提取一个文本中两行已知内容之间的内容?

浏览:40日期:2023-04-25

问题描述

请问如何提取一个文本中两行已知内容之间的内容。比如在某hosts文件中存在如下内容。

……Localhost (DO NOT REMOVE)127.0.0.1 localhost255.255.255.255 broadcasthost::1 localhostfe80::1%lo0 localhostModified hosts start……

我想要提取“Localhost (DO NOT REMOVE)”和“Modified hosts start”中的内容到另外一个文本中。应该怎么解决呢?我使用的如下代码哪里有问题呢?

char str[256],start1[256],end1[256]; strcpy(start1,'# Localhost (DO NOT REMOVE)'); strcpy(end1,'# Modified hosts start'); while (!feof(fstream_backup)){fgets(str,1024,fstream_backup);if (strcmp(str, start1)==0){ while (strcmp(str, end1)!=0){fgets(str,1024,fstream_backup);fprintf(fstream_out,'%s',str); } } }

谢谢。

问题解答

回答1:

#include <iostream>#include <fstream>#include <string>using namespace std;int main(){ bool flag = false; ifstream file1('file1.txt'); ofstream file2('file2.txt'); string line, des1('Localhost (DO NOT REMOVE)'), des2('Modified hosts start'); while (getline(file1, line)) {if (line == des1) { flag = true; continue;}if (line == des2) break;if (flag) file2 << line << endl; } file1.close(); file2.close();}

既然是C++下,建议这样写。

回答2:

这样的需求为什么要用c++这么笨重的语言,shell就可以优雅的搞定了下面语句可以输出line1和line5之间的文本

cat file1 | sed -n /line1/,/line2/p | sed /line1/d | sed /line2/d > file2

相关文章: