1

I was wondering if anyone knew how I could go about writing a grep command that recursively finds files that are not being referenced/used in a specific file and/or a directory of files, and then delete them?

So for example if my file has this

<head>
    <link rel='stylesheet' href='path/to/a.css'/>
    <script src='path/to/a-min.js></script>
</head>

And my folder has this

/assets
-- /css
---- a.css
---- b.css
-- /js
---- a-min.js
---- /b
------ b-min.js
---- /c
------ c-min.js

It will recursively delete all the ones not referenced in said file which would be b.scss, b-min.js, and c-min.js. Of course if another file has those files referenced, it wouldn't delete them.

I use version control so it isn't an issue if they get deleted and it screws up but it would be nice if there was a simple command or automated way of doing this correctly. Advice on best practice?

  • 2
    Parse the HTML with a real parser (perl, python, ruby) and keep a list reffed of files referenced, then walk over the list of files and compare to reffed – Anthon Oct 23 '14 at 19:51
  • Hmm I see -- I know html parsing should be done with proper tools. I'll probably explore some options including python. Actually, we're moving most of our stuff to nodejs which has ways to parse html so I'm gonna look into that as well. – aug Oct 23 '14 at 21:37
  • Quick and dirty? use grep and either cut or awk to extract the files mentioned by href, sort, uniq, and write to a file. The use find -type file to find all files, and grep -vf the files not in the html. – ChuckCottrill Oct 23 '14 at 23:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.