I need to add PHP tags surrounding a file. It's easy to append them using
find . -exec echo "?>" >> '{}' \;
but how can I prepend the tag <?php?
I need to add PHP tags surrounding a file. It's easy to append them using
find . -exec echo "?>" >> '{}' \;
but how can I prepend the tag <?php?
sed -i "1s/^/<?php /" file
(The -i is for in-place edit.)
More portable version:
ed file <<!
1s/^/<?php /
wq
!
You can do that with a perl one-liner:
perl -0777 -p -i -e "s/^/hey /g" testfile
The -0777 forces file-slurping mode, so the entire file is read as one line. -p enables looping. -i enables in-place editing of the file. ^ indicates the beginning of a line.
$ cp testfile1 testfile; perl -0777 -p -i -e "s/^/hey /g" testfile; diff testfile testfile1
1c1
< hey asdf
---
> asdf
Update: As indicated in the comments, you can choose to auto-generate a backup by using -i.bak instead of -i. This provides additional safety in case of errors in your command. The argument to -i becomes the suffix of the backup.
When updating a bunch of files, you could run the command with -i.backup${RANDOM}, check that all files updated correctly, then remove all files with that extension.
You could use an AWK filter like this,
awk '{if(NR==1) printf "%s%s","PREFIX",$0; else print $0}' testfile > newfile
Where PREFIX is your php prefix string.
I can't leave a comment yet, but to do it all in one step:
find . -type f -exec sed -i -e "1s/^/<?php /" -e "\$s/\$/ ?>/" {} \;
sed is for editing streams -- a file is not a stream. Use a program that is meant for this purpose, likeed or ex. The -i option to sed is not only not portable, it will also break any symlinks you may encounter, since it essentially deletes it and recreates it, which is pointless.
for file in foo bar baz; do
ed -s "${file}" << EOF
0a
<?php
.
w
EOF
done
An alternative to what you wrote for adding something to the end of every file in the directory (in bash):
for FNAME in *
do
echo "?>" >> $FNAME
done
though I do like your find one-liner :)