remove blank first line script

*爱你&永不变心* 提交于 2019-12-25 03:39:18

问题


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/

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/14341815/remove-blank-first-line-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!