20

Lets suppose I have files on my harddisk having extensions as .md.

I want to convert all those files to .html through find and the -exec option.

The command to convert a markdown file to html is

markdown readme.md > readme.html

I am trying to use something like:

find / -name "*.md" -type f -exec markdown {} > {}.html \;

Of course, the above doesn't work. So, how do I do that using only find and exec?

1
19

You need to quote around the construct containing > because it's a shell special character, like this:

find / -name "*.md" -type f -exec sh -c 'markdown "$0" > "$0.html"' {} \;

This will also rename the files so you end up with foo.html instead of foo.md.html:

find / -name "*.md" -type f -exec sh -c 'markdown "${0}" > "${0%.md}.html"' {} \;
6
  • Don't you get file.md.html now? Instead of file.html?
    – Bernhard
    Jul 21 '12 at 17:42
  • @rush Why do I need {} at the end in both commands? Also, in the second command, it's hard to follow for me as to what happened? I didn't understand the ${0%.md}/.html part. Jul 22 '12 at 9:50
  • Btw, I just checked. you probably wrote forward slash by mistake in ${0%.md}/.html. Jul 22 '12 at 10:00
  • @shadyabhi The final {} is the input argument for the sh -c string, and is there accessed as $0. The command you don't understand strips .md and adds .html. You're probably right with escaping the .
    – Bernhard
    Jul 22 '12 at 10:37
  • @Bernhard Thanks for your reply. Honestly, I knew earlier also that it's stripping .md and adding .html but I would like to know more about it. Can you redirect me to a wiki/doc that explains this? Jul 22 '12 at 11:56
0

The way to achieve exactly what you have written is to use markdown's -o option, which specifies the name of the output file, i.e.

find / -name "*.md" -type f -exec markdown -o {}.html {} \;

Doing it this way avoids starting a new shell just to run markdown.

Unfortunately, as Bernhard points out, doing it this way gives you files named file.md.html instead of file.html, so rush's approach is more appropriate here.

4

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.