I have this script which is printing out the files that have the first line blank:
for f in `find . -regex ".*\.php"`; do
for t in head; do
$t -1 $f |egrep '^[ ]*$' >/dev/null && echo "blank line at the $t of $f";
done;
done
How can I improve this to actually remove the blank line too, or at least copy all the files with the blank first line somewhere else.
I tried copying using this, which is good, because it copies preserving the directory structure, but it was copying every php file, and I needed to capture the postive output of the egrep and only copy those files.
rsync -R $f ../DavidSiteBlankFirst/
Just using
find
andsed
:The
-type f
option only find files, not that I expect you would name folders with a.php
suffix but it's good practice. The use of-regex '.*\.php'
is overkill and messier just using globbing-name "*.php"
. Use find's-exec
instead of a shell script, thesed
script will operate on each matching file passed byfind
.The
sed
script looks at the first line only1
and applies the operations inside{}
to that line. We check if the line is blank/^\s*$/
if the line matches we deleted
it and quitq
the script so not to read all the other lines in the file. The-i
option saves the change back to the file as the default behaviour ofsed
is to print tostdout
. If you want back files making use-i~
instead, this will create a backfilefile~
forfile
.I would use sed personally
this finds all the regular files ending in .php and executes the sed command which works on the first line only and checks to see if its blank and deletes it if it is, other blank lines in the file remain unaffected.