1

我有 50 个具有此功能的文件

public function __construct()
    {   $this->createdAt = new DateTime();
        $this->updatedAt = new DateTime();
        $this->isActive = true;
        $this->isDeleted = false;
    }

现在有什么方法可以使用 sed 或 awk 或任何可能的方式在所有文件中的该函数中附加这些行

就像假设 file.php 是

public function __construct()
    {
        $this->age = 20;

    }

我希望它应该变成这样

public function __construct()
    {
        $this->age = 20;
        $this->createdAt = new DateTime();
        $this->updatedAt = new DateTime();
        $this->isActive = true;
        $this->isDeleted = false;

    }
4

2 回答 2

2

这可能对您有用(GNU sed):

cat <<\! >append.txt
>         $this->createdAt = new DateTime();
>         $this->updatedAt = new DateTime();
>         $this->isActive = true;
>         $this->isDeleted = false;
> !
cat <<\! >file
> public function __construct()
>     {
>         $this->age = 20;
> 
>     }
> !
sed '/$this->age = 20/r append.txt' file
public function __construct()
    {
        $this->age = 20;
        $this->createdAt = new DateTime();
        $this->updatedAt = new DateTime();
        $this->isActive = true;
        $this->isDeleted = false;

    }
sed -i '/$this->age = 20/r append.txt' file{1..50} # file1 to file50

编辑:

在闭合花括号之前插入:

sed -i '$!s/$/\\/' append.txt
sed -i '/^public function __construct()/,/^\s*}/!b;/^\s*}/i\'"$(<append.txt)" file{1..50}
于 2012-08-02T19:54:07.680 回答
0
$ sed -i 's/\$this->age = 20\;/\$this->age = 20\;\n\t\$this->createdAt = new DateTime()\;\n\t\$this->updatedAt = new DateTime()\;\n\t\$this->isActive = true\;\n\t\$this->isDeleted = false\;/g' file.php
于 2012-08-02T09:31:51.553 回答