我有大约 13,000 个文件需要从中删除面包屑。每个文件开头的模式大致如下所示:
Title
=====
| |image0| `link <link1.html>`__ |image1| ::
`link2 <link2.html>`__ ::
`link3 <link3.html>`__
| **Introduced** : VersionXXX
然而,在某些文件中,标题行和最后一行之间的部分是 2 或 4,具体取决于树的深度。无论标题行和此处显示的最后一行之间的行如何,我都希望完全删除中间部分。我不太清楚如何做到这一点,希望能得到一些帮助。我正在使用 pycharm,他们有一个正则表达式工具(我还没有成功使用过),但我同样乐于使用 sed 或 python 等替代方法来遍历文件。
预期结果:
Title
=====
| **Introduced** : VersionXXX
感谢所有出色的解决方案。 最终解决方案以避免写入单独的文件:
import os
src_dir = '/PycharmProjects/docs/testfiles'
logf = open('failed_file_log.txt', 'w')
for filename in os.listdir(src_dir):
print(filename)
with open('{}/{}'.format(src_dir, filename), 'r') as f:
lines = f.readlines()
with open('{}/{}'.format(src_dir, filename), 'w') as f:
try:
for i in range(3):
f.write(lines[i])
copy = False
for line in lines:
if copy:
f.write(line)
elif line.startswith('| **Introduced**'):
copy = True
f.write(line)
except Exception as e:
logf.write('Failed to rewrite {}'.format(filename))
finally:
pass
最佳答案
由于 sed
被 OP 在问题中标记,以下是获得所需结果的两个单行代码:
sed -n '/Title/{N;N;p}; /Introduced/{p}' input
Title
=====
| **Introduced** : VersionXXX
或者
awk
:
awk '/Title/{print;getline;print;getline;print}/Introduced/{print}' input
Title
=====
| **Introduced** : VersionXXX
关于python - 从pycharm中重组的文本文件中删除面包屑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56548015/