如何从文件中删除多行字符串/文本模式块?

如何从文件中删除多行字符串/文本模式块?

我有一个文本文件,其中包含多行文本字符串,我想扫描该文件并删除它找到的该多行且有时可能重复的字符串的所有实例。

示例字符串:

recursive-test yes;
test-limit{
tests 10;
};
location "testLoc" {
type test;
};
location "testLoc2"{
type test;
file "/etc/var/test.sql";
};
include "/etc/var/test.conf";
};



recursive-test yes;
test-limit{
tests 10;
};
location "testLoc" {
type test;
};
location "testLoc2"{
type test;
file "/etc/var/test.sql";
};
include "/etc/var/test.conf";
};

otherTestTextHere
123
321

recursive-test yes;
test-limit{
tests 10;
};
location "testLoc" {
type test;
};
location "testLoc2"{
type test;
file "/etc/var/test.sql";
};
include "/etc/var/test.conf";
};

正如你所看到的,文本文件中重复的文本字符串总是相同的,从字符串的开头,到多行的结尾,它总是相同的:

recursive-test yes;
test-limit{
tests 10;
};
location "testLoc" {
type test;
};
location "testLoc2"{
type test;
file "/etc/var/test.sql";
};
include "/etc/var/test.conf";
};

多行字符串通常不应重复,但作为一种故障保护,我还在寻找一种方法,该方法将只扫描所有实例,并在由于某种原因该字符串从写入文本文件的另一个应用程序中重复时将其完全删除。

使用sed我只能弄清楚如何一次删除一行,但这对我不起作用,因为有时多行字符串中某些行上的某些单词会出现在其他类似的多行字符串中,但我想保持。我真的只是想从字符串的开头到结尾搜索这个多行字符串的“精确”重复项。

我试图将其保留为单行命令行/优化。

答案1

我如何理解OP有一些由空行分隔的文本块,OP想要删除所有重复项:

awk -v RS='\n\n' -v ORS="\n\n" '!seen[$0]++' file

如果OP只想删除该块,请尝试通过GNU sed:

sed -z 's~recursive-test yes;\ntest-limit{\ntests 10;\n};\nlocation "testLoc" {\ntype test;\n};\nlocation "testLoc2"{\ntype test;\nfile "/etc/var/test.sql";\n};\ninclude "/etc/var/test.conf";\n};~~g' file

答案2

< input python -c 'import sys; sys.stdout.write(sys.stdin.read().replace("""recursive-test yes;\ntest-limit{\ntests 10;\n};\nlocation "testLoc" {\ntype test;\n};\nlocation "testLoc2"{\ntype test;\nfile "/etc/var/test.sql";\n};\ninclude "/etc/var/test.conf";\n};""", ""))'

python 的三引号 ( """) 很好地帮助您不必转义字符串中的引号即可进行匹配。

相关内容