Reputation: 31
I have a directory containing many different folders. In these are some php files. I need to change line nr 1 in all files that match a certain string, in all those folders.
All the files I need to change look something this on line nr 1: <?php some text><?php
I need to replace all those 1st lines with "<?php
"
I tried this:
grep -rl something /somedir/folder/ | xargs sed -i '' '1s/.*/<?php/
But it only replaces one of the files in the first folder.
I also tried:
grep -rnw something /somedir/folder/ | xargs sed -i '' '1s/.*/<?php/
But then I get this error:
sed: /somedir/folder//1.php:1:<?php: No such file or directory
Any idea how I can fix this?
Upvotes: 1
Views: 182
Reputation: 31
I found the solution. Now, since I am on OSX, apparently sed does not work exactly the same way as on Linux. Which I did not know. But this is how it can be done:
find ./ -name \*.php -exec sed -i '' -e '1s/.*/<?php/' {} \;
I don't understand exactly why it needs to be like this, but it works.
Upvotes: 0
Reputation: 31
grep -rl something /somedir/folder/ | xargs sed -i '' '1s/.*/<\?php/'
This sort of works. But it only changes the file it finds first. And not all files. So basically with this I would have to run it 100 times if I have 100 files =)
Any idea how I can get around that?
Upvotes: 0
Reputation: 7302
sed -i -e 's/<\?php.*<\?php/<?php/' `find ./ -type f`
To explain:
sed -i
Run, with sed editing in-place
-e 's/
a replacement command, replacing
<\?php.*<\?php
two consecutive php opening statements (escaping the question marks, because this is a regex)
/
with
<?php
one php opening statement
/'
once per line.
`find ./ -type f`
for everything in this folder that's a file.
Upvotes: 2
Reputation: 51938
I don't know what the intention of the empty string was, when executing sed. Without it it works totally fine for me:
grep -rl something /somedir/folder/ | xargs sed -i '1s/.*/<\?php/'
Upvotes: 0
Reputation: 3141
find ./ -iname "*.php" -exec sed '1 s/^<?php some text><?php$/<?php/' -i {} \;
Upvotes: 0