python - 通过模式匹配从多个文件中提取行并将其写入Linux中的另一个文件

标签 python linux bash

我有 20 个文件。我想通过匹配模式 '<script src="{%.*%}>' 来提取行从这 20 个文件中提取这些行并将这些行写入新文件。

我还想从原始文件中删除这些行。

除了我尝试过的糟糕方法之外,还有更好的方法吗?

这是我的尝试:

import os
import sh

folder_path='/home/username/folder/'
match_phrase = '<script src="{%'
new_file = '/home/username/file.txt'

files = os.listdir(folder_path)
print files
for file in files:
    full_filename = folder_path + file
    lines=[]
    line_nos=[]

    with open(full_filename) as myFile:
        for num, line in enumerate(myFile, 1):
            if match_phrase in line:
                line_nos.append(num)
                lines.append(line)
        print lines
        print line_nos

        with open(new_file,'a') as newfile:
            for line in lines:
                newfile.write(line)

    for del_line in line_nos:
        print "deleting line %s from file=%s"%(del_line,full_filename)
        del_line=str(del_line)+'d'
        sh.sed('-i',del_line,full_filename)

最佳答案

使用sed:

sed -i -e "/$pattern/w $newfile" -e "/$pattern/d" $files

Sedw 命令将匹配项写入其他文件。 d 将其删除。

<小时/>

示例:

$ pattern='<script src="{%'
$ files=/home/username/folder/*
$ newfile=/home/username/file.txt
$ 
$ sed -i -e "/$pattern/w $newfile" -e "/$pattern/d" $files

关于python - 通过模式匹配从多个文件中提取行并将其写入Linux中的另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37203994/

相关文章:

python - python中的索引列表,用于一系列值

python - 如何在Python中实现线程运行两个bash shell命令?

linux - Bash:循环从 CSV 中一次读取 N 行

查找斐波那契数列的 Python 程序。更Pythonic的方式

python - 处理异常的首选方法是什么?

c++ - 使用 qhash->keys 初始化 qlist

python - 在 jupyter/ipython notebook 中设置优先级/niceness

linux - 如何在以逗号分隔的单行中列出 ps -U root -u root -eo pid 的输出

linux - 遍历一个表并将该表的信息附加到另一个文件

python - 如何并行运行带参数的函数?