Bash使用awk查找并替换文件中的记录

时间:2015-03-13 10:27:28

标签: regex bash awk

我正在寻找一种方法来直接在文件中用新记录替换用awk找到的记录。

cat file

    public function method1()
    {
        return 1;
    }

    /**
     * old comment
     */
    public function oldMethod()
    {
        return 'old';
    }

    public function method3()
    {
        return 3;
    }

awk因此返回

awk 'BEGIN{RS="\n\n"; IGNORECASE=1} /oldMethod/ {print $0}' file
    /**
      * old comment
      */
    public function oldMethod()
    {
        return 'old';
    }

更新预期的输出,例如:

cat file

    public function method1()
    {
        return 1;
    }

    /**
     * new comment
     */
    public function newMethod()
    {
        /*Do some fancy stuff here*/
        return 'another output';
    }

    public function method3()
    {
        return 3;
    }

现在我想用变量中包含的方法替换此方法。 我不知道如何实现这一目标。 有没有人有个好主意?

最诚挚的问候 nTOXIC

2 个答案:

答案 0 :(得分:2)

$ cat input.c

public function method1()
{
    return 1;
}

/**
 * old comment
 */
public function oldMethod()
{
    return 'old';
}

public function method3()
{
    return 3;
}

-

$ cat newfile.c
/**
 * new comment
 */
public function newMethod()
{
    /*Do some fancy stuff here*/
    return 'another output';
}

-

$ awk -v RS= -v ORS=$'\n' 'NR==FNR{a=a $0 "\n"; next;}/oldMethod/{print ORS a; next;}1' newfile.c input.c

public function method1()
{
    return 1;
}

/**
 * new comment
 */
public function newMethod()
{
    /*Do some fancy stuff here*/
    return 'another output';
}

public function method3()
{
    return 3;
}

说明:

  1. -v RS=将RS设置为空字符串:表示用空行分隔记录。
  2. -v ORS=$'\n'输出记录分隔符。
  3. 'NR==FNR{a=a $0 "\n"; next;}'在名为a的变量中捕获第一个文件。转到下一条记录。
  4. '/oldMethod/{print ORS a; next;}1'对于记录匹配/ pattern /,请打印a。其他印刷记录。
  5. newfile.c是第一个文件。 input.c是参数列表中的第二个文件。

答案 1 :(得分:1)

您只需要:

awk -v new="$var" -v RS= -v ORS='\n\n' '/oldMethod/{$0=new}1' file

请参阅:

var=$(cat << '_EOF_'
/**
 * new comment
 */
public function newMethod()
{
    /*Do some fancy stuff here*/
    return 'another output';
}
_EOF_
)

$ awk -v new="$var" -v RS= -v ORS='\n\n' '/oldMethod/{$0=new}1' file 
public function method1()
{
    return 1;
}

/**
 * new comment
 */
public function newMethod()
{
    /*Do some fancy stuff here*/
    return 'another output';
}

public function method3()
{
    return 3;
}

如果需要更多,请将/oldMethod/更改为您要搜索的旧记录的大部分内容。如果要在变量中指定,只需将命令行更改为:

awk -v new="$var" -v old="oldMethod" -v RS= -v ORS='\n\n' '$0~old{$0=new}1' file

与@ anishane的答案相比,如果你有&#34; new&#34;记录在文件而不是变量中,只需要:

awk -v RS= -v ORS='\n\n' 'NR==FNR{new=$0;next} /oldMethod/{$0=new}1' newfile.c input.c