Append a text to the end of multiple files in Linux

前端 未结 6 1429
囚心锁ツ
囚心锁ツ 2021-02-05 01:05

I need to append the following code to the end to all the php files in a directory and its sub directory:

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-05 01:40

    You can use sed combined with find. Assume your project tree is

        /MyProject/ 
        /MyProject/Page1/file.php
        /MyProject/Page2/file.php
        etc.        
    
    1. Save the code you want to append on /MyProject/. Call it append.txt
    2. From /MyProject/ run:

      find . -name "*.php" -print | xargs sed -i '$r append.txt'
      

      Explain:

      • find does as it is, it looks for all .php, including subdirectories
      • xargs will pass (i.e. run) sed for all .php that have just been found
      • sed will do the appending. '$r append.txt' means go to the end of the file ($) and write (paste) whatever is in append.txt there. Don't forget -i otherwise it will just print out the appended file and not save it.

    Source: http://www.grymoire.com/unix/Sed.html#uh-37

提交回复
热议问题