sed パターンマッチングとファイル挿入

sed パターンマッチングとファイル挿入

sedを使用してファイルを編集しようとしているときにsetup.py一致する必要があるパターンは次のとおりです。

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import fnmatch
import os
import re
import sys

from setuptools import Command
from setuptools import find_packages
from setuptools import setup
from setuptools.command.install import install as InstallCommandBase
from setuptools.dist import Distribution

DOCLINES = __doc__.split('\n')

_VERSION = '1.0.0'

REQUIRED_PACKAGES = [
    'absl-py >= 0.7.0',
    'astunparse == 1.6.3',
    'backports.weakref >= 1.0rc1;python_version<"3.4"',
    'scipy == 1.2.2;python_version<"3"',
]

一致後、endの前に行を挿入したいと思いますREQUIRED_PACKAGES = [ .* ]'test == 1.1.0',]

だから結局、次のように見えます。

REQUIRED_PACKAGES = [
    'absl-py >= 0.7.0',
    'astunparse == 1.6.3',
    'backports.weakref >= 1.0rc1;python_version<"3.4"',
    'scipy == 1.2.2;python_version<"3"',    
    'test == 1.1.0',
]

Pythonを試してみましたが、よりクリーンでシンプルなオプションを探していました。

import re


SEARCH_DICT = {
    'required_packages': re.compile(
        r'REQUIRED_PACKAGES = (?P<required_packages>.*)\n')
}

TEST_LIBRARY = '\t\t\'test==1.0.0\'\n'


def _parse_line(line):
    """
    Do a regex search against all defined regexes and
    return the key and match result of the first matching regex

    """

    for key, rx in SEARCH_DICT.items():
        match = rx.search(line)
        if match:
            return key, match
    # if there are no matches
    return None, None


def parse_file(filepath):
    """
    Parse text at given filepath

    Parameters
    ----------
    filepath : str
        Filepath for file_object to be parsed

    Returns
    -------
    data : file contents
    """

    data = []  # create an empty list to collect the data
    line_index = -1 
    # open the file and read through it line by line

    with open(filepath, 'r+') as file_object:
        line = file_object.readline()
        line_index+=1
        while line:
            # at each line check for a match with a regex
            key, match = _parse_line(line)
            if key == 'required_packages':
                required_packages_start = match.group('required_packages')
                if required_packages_start == '[':                    
                    print('Found REQUIRED_PACKAGES')
                    while line.strip():                        
                        library = line.rstrip()
                        if library == ']': # End of required packages
                            return line_index
                        line = file_object.readline()
                        line_index+=1                     

            line = file_object.readline()  
            line_index+=1          
        file_object.readline()
        line_index+=1

    return line_index


line_index = parse_file('test.test')
lines = None
if line_index:
    with open('test.test', 'r') as file_handler:
        lines = file_handler.readlines()
    lines.insert(line_index, TEST_LIBRARY)
    with open('test.out', 'w') as file_handler:
        file_handler.writelines(lines)

ベストアンサー1

sed行を挿入できますi

sed "/REQUIRED_PACKAGES = \[/, /]/ {/]/i\    'test == 1.1.0',
;}" FILE

おすすめ記事