tags:

views:

26

answers:

2

I'm looking for a sed command that, with find, I can take a directory tree of JSP files and write the name of the file in an HTML comment to the top of the file.

This will allow me to review a legacy application JSP call tree of in the HTML source.

I'm thinking it will be a one liner for a talented sed guru...

something like:

find . -name '.jsp' -exec sed ? ? ? {} \;

Maybe something using xargs is more appropriate, but I think sed is the tool that will do the work.

+1  A: 

On Unix the filename will contain slashes (/) which are special characters for sed, so I would recommend this simpler approach that writes the filename at the bottom of the file:

find . -name '*.jsp' -exec sh -c "echo '<\!-- {} -->' >> '{}'" \;

To write the filename at the top of the file use this:

find . -name '*.jsp' -exec sh -c \
     'echo "<!-- {} -->" > "{}.new" && cat "{}" >> "{}.new" && mv "{}.new" "{}"' \;

N.B. The filename might contain characters that might render your HTML invalid, e.g. &, although I doubt that a JSP could have such a strange name.

Cristian Ciupitu
That will add the comment at the end of the file.
Dennis Williamson
@Dennis Williamson: you're right. I missed that part from the question. I added the solution for the top of the file.
Cristian Ciupitu
+1  A: 

If you want to use sed, you can try

find -name "*.jsp" -exec sed -i '1i <!-- {} -->' {} \;

Works fine for me in the presence of /.

Michael Mior
You're right. I was thinking of using the substitute command, not the insert command which doesn't have any problems with `/`.
Cristian Ciupitu
You can use characters other than `/` as delimiters in an `s` command in `sed`.
Dennis Williamson