Irina
Irina

Reputation: 784

How to add a line in files recursively bash?

I use the command to add one line at the beginning of the php files in the current directory and its subdirrectories recursively.

    find . -name "*.php" -exec sed -i -e "/<?php/a\\
Sometext" *.php \;

But it adds Sometext many times (instead of one) only in php files in the current directory (instead of all). What I did wrong?

Upvotes: 1

Views: 960

Answers (1)

Socowi
Socowi

Reputation: 27330

You don't pass the files found by find to the sed command, but the files found by the shell glob *.php. Before find is executed, the *.php is expanded and your command becomes

find . -name '*.php' -exec sed ... 1stMatch.php 2ndMatch.php ... \;

Afterwards, find will for each found file execute the command

sed ... 1stMatch.php 2ndMatch.php ...

You probably wanted to write

find . -name '*.php' -exec sed -i -e '/<?php/a\\
Sometext' {} \;

For each file, find executes sed and replaces {} by one file name. In this case, you could even write {} + instead of {} \; such that sed is executed only once on all files at once, instead of once for every file – this will speed up your command drastically.

Upvotes: 6

Related Questions