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/
I would use sed personally
find ./ -type f -regex '.*\.php' -exec sed -i -e '1{/^[[:blank:]]*$/d;}' '{}' \;
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.
Just using find
and sed
:
find . -type f -name "*.php" -exec sed -i '1{/^\s*$/d;q;}' {} \;
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, the sed
script will operate on each matching file passed by find
.
The sed
script looks at the first line only 1
and applies the operations inside {}
to that line. We check if the line is blank /^\s*$/
if the line matches we delete d
it and quit q
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 of sed
is to print to stdout
. If you want back files making use -i~
instead, this will create a backfile file~
for file
.