Software
Insert text from a file recursively using sed
To add some context, my goal here was to insert a copyright statement at the start of each PHP file present in my working directory. I knew how to replace the content of a file with the sed utility, so I first started to look for a way to read input from a file.
It appears that the GNU version of sed can do it by using the r option, which stands for "read". So to make sed insert the content of a file named header after the first line of the PHP file source.php:
$ sed '1r header' source.php > source.php.temp
The use of redirections force us to create a temporary file. Redirecting directly to source.php would give us an empty file! Fortunately, there is a utility called sponge, from a collection of tools called moreutils1, which allows us to redirect the modified content to the same source.php file:
$ sed '1r header' source.php | sponge source.php
Now, all there is left to do is executing that command on each PHP file present in the main directory and all its subfolders. For that, I just wrote a for loop in a bash script but I learned how to select all the files recursively using the following glob pattern: **/*.php
This is available from bash v4 and to use it in a script, just add the following line before:
shopt -s globstar
1 The moreutils package is available on Arch Linux in the community repository.
Comments
No comment yet.
A remark, a suggestion? Do not hesitate to express yourself below. Just be courteous and polite, please.