如何使用shell脚本或python或p替换源文件中的代码块

2024-04-26 07:39:59 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的源文件中有多个if子句具有相同的检查。我想通过注释掉基于if语句后定义的文本的条件语句,使一个条件块一直执行。在

if [ "${SVR_GRP}" = "obi" ] ; then
  EXTRA_JAVA_PROPERTIES="-Doracle.fusion.appsMode=true ${EXTRA_JAVA_PROPERTIES}"
  export EXTRA_JAVA_PROPERTIES
fi

if [ "${SVR_GRP}" = "obi" ] ; then
   EXTRA_JAVA_PROPERTIES="-DUseSunHttpHandler=true ${EXTRA_JAVA_PROPERTIES}"
   export EXTRA_JAVA_PROPERTIES
fi

替换为

^{2}$

您能建议我如何使用perl/python或shell脚本来实现这一点吗?在

我试过perl命令,但对我不起作用

perl -0pe '/if [ "${SVR_GRP}" = "obi" ] ; then\nEXTRA_JAVA_PROPERTIES="-DUseSunHttpHandler=true ${EXTRA_JAVA_PROPERTIES}"/#if [ "${SVR_GRP}" = "obi" ] ; then\nEXTRA_JAVA_PROPERTIES="-DUseSunHttpHandler=true ${EXTRA_JAVA_PROPERTIES}"

Python程序的工作如预期,但认为它是一个变通办法,觉得可以有更好的解决方案。我不擅长shell脚本和perl。在

file_loc = 'D:/official/workspace/pythontest/test/oops/test.sh'
new_file_loc = 'D:/official/workspace/pythontest/test/oops/test1.sh'


def modify():
    file = open(file_loc)
    file2 = open(new_file_loc, 'w')
    lines = []
    count = -1;
    found = False
    for line in file:
        if str(line).strip() == 'if [ "${SVR_GRP}" = "obi" ] ; then':
            count = 3;
            lines.append(line)
        else:
            if str(line).strip() == 'EXTRA_JAVA_PROPERTIES="-DUseSunHttpHandler=true ${EXTRA_JAVA_PROPERTIES}"':
                found = True
            lines.append(line)
            count = count - 1;
        if (count == 0):
            writeIntoFile(file2, lines, found)
            found = False
            count = -1
            lines = []
        elif count < 0:
            lines = []
            file2.write(line)


def writeIntoFile(file, lines, found):
    for line in lines:
        if found == False:
            file.write(line)
        elif str(line).strip() == 'if [ "${SVR_GRP}" = "obi" ] ; then' or str(line).strip() == 'fi':
            file.write('#' + line);
        else:
            file.write(line)


modify()

Tags: trueifcountlinepropertiesjavaextrafile
1条回答
网友
1楼 · 发布于 2024-04-26 07:39:59

I want comment out condition based on second line text value

恐怕这是一个非常不清楚的规格。请更努力地解释你的文本需要发生什么。在

这段Perl代码将示例输入转换为示例输出,但是考虑到问题的模糊性,不可能知道它是否出于正确的原因进行了正确的转换。在

它是一个Unix过滤器(它从STDIN读取并写入STDOUT)。在

#!/usr/bin/perl

use strict;
use warnings;

local $/ = ''; # Paragraph mode

my %seen;

while (<>) {
  my $first_line = (split /\n/)[0];
  if ($seen{$first_line}++) {
    s/^if\b/#if/m;
    s/^fi\b/#fi/m;
  }

  print;
}

相关问题 更多 >