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 に答える