I'm trying to use tesseract and hocr2pdf on a series of .tif files in a folder.

Using ls *.tif | xargs -I% tesseract % % -l fra hocr produces the html files which have the same file name but with .html added. But ls *.tif |xargs -I% hocr2pdf -i % -n -o %.pdf < %.html is not working. I get the error message %.html not found. It seems xargs is having problems with the < in the hocr2pdf command.

How do I circumvent this?


xargs isn't ideal for this task. You need a shell for redirection.

One option would be to invoke bash from xargs, but it's much simpler to use a for loop:

for f in ./*.tif; do
    tesseract "$f" "$f" -l fra hocr
    hocr2pdf -i "$f" -n -o "$f.pdf" < "$f.html"
  • Out of curiosity, why ./*.tif instead of *.tif? – terdon Mar 23 '13 at 16:42
  • 1
    If a filename starts with a hyphen-minus, it might get interpreted as a switch with argument. For example, the filename -in.tif would become -i n.tif. The leading ./ avoids this. – Dennis Mar 23 '13 at 16:51
  • How do I make this recursive? – To Do May 19 '13 at 14:26

First of all, never parse the output of ls.

Now, the reason it's not working is that xargs does not see the %.html, bash does. The < is taken to be the end of the xargs command, therefore the substitution you have set up (-I%) no longer works. A better way to do what you want would be something like this:

find . -maxdepth 1 -name "*.tif" -print0 | while IFS= read -r -d '' n; do 
    tesseract "$n" "$n" -l fra hocr &&
    hocr2pdf -i "$n.html" -n -o "$n.pdf"
  • 1
    No worries, haha. Minor obsession of mine, sorry. Beware that this is recursive, while the OP's ls *.tif is not. – slhck Mar 23 '13 at 16:36
  • True. All things considered, using a for loop as @Dennis suggested is better. – terdon Mar 23 '13 at 16:39

With GNU Parallel you can get the processing parallelized:

parallel "tesseract {} {} -l fra hocr; hocr2pdf -i {} -n -o {}.pdf < {}.html" ::: *.tif

It takes literally 10 seconds to install GNU Parallel:

wget pi.dk/3 -qO - | sh -x

Watch the intro videos to learn more: https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1

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.