<分区>
我在网上搜索但没有确切地知道如何去做,因为我能够编写的代码只是针对模式的一次出现,但是如果该模式有不同的出现行??
<分区>
我在网上搜索但没有确切地知道如何去做,因为我能够编写的代码只是针对模式的一次出现,但是如果该模式有不同的出现行??
最佳答案
如果您使用的是 Unix 或类似系统(如 Linux 或 MacOS X),那么您已经有一个命令行程序可以执行此操作:sed
。
否则你必须从原始文件中读取并写入一个新文件,在读取和写入时替换文本。之后,您必须将新文件重命名为旧的原始文件。
至于文本的实际查找,如果它是一个固定的字符串,您可以使用例如strstr
,否则请查看 regular expressions .
编辑: 如何使用 sed(1)
进行编辑:
$ sed -i 's/xyz/abc/g' infile.txt
上述命令将读取 infile.txt
,将所有出现的文本 xyz
替换为 abc
并将其写回 infile.txt
.
编辑:如何搜索/替换:
FILE *input = fopen("input.txt", "r");
FILE *output = fopen("temp.txt", "w");
char buffer[512];
while (fgets(buffer, sizeof(buffer), input) != NULL)
{
/* The text to find */
static const char text_to_find[] = "xyz";
/* The text to replace it with */
static const char text_to_replace[] = "abc";
char *pos = strstr(buffer, text_to_find);
if (pos != NULL)
{
/* Allocate memory for temporary buffer */
char *temp = calloc(
strlen(buffer) - strlen(text_to_find) + strlen(text_to_replace) + 1, 1);
/* Copy the text before the text to replace */
memcpy(temp, buffer, pos - buffer);
/* Copy in the replacement text */
memcpy(temp + (pos - buffer), text_to_replace, strlen(text_to_replace));
/* Copy the remaining text from after the replace text */
memcpy(temp + (pos - buffer) + strlen(text_to_replace),
pos + strlen(text_to_find),
1 + strlen(buffer) - ((pos - buffer) + strlen(text_to_find)));
fputs(temp, output);
free(temp);
}
else
fputs(buffer, output);
}
fclose(output);
fclose(input);
/* Rename the temporary file to the original file */
rename("input.txt", "temp.txt");
此代码已被tested to work .
注意:如果你不知道什么是指针运算,那么上面的代码可能很难理解,你只需要相信我它做了它应该做的事。 :)
关于C 程序将文本文件中的模式 "find"替换为 "replace"作为输入和输出文件应该具有替换模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12280008/