4

I have a folder called X which inside has many folders and sub-folders. I want to search in all of the folders inside X and find a specific document type. For example xlsx and transform each file into an xls file. In this case I need to use the libreoffice convert option like libreoffice --headless --convert-to xls but here is the catch. After conversion each converted file should be in the same folder as the original xlsx file.

Example:

X/
 Folder 1/
 Folder 2/
         Folder 2.1/file.xlsx
 Folder 3/
 Folder 4/
         Folder 4.1/anotherFile.xlsx

After conversion:

X/
 Folder 1/
 Folder 2/
         Folder 2.1/file.xls
         Folder 2.1/file.xlsx
 Folder 3/
 Folder 4/
         Folder 4.1/anotherFile.xls
         Folder 4.1/anotherFile.xlsx

The new xls* in this case, will be converted on the same folder as the original xlsx. This will be done inside all sub-folders and to all xlsx that are found.

Luis Alvarado
  • 216,643

2 Answers2

3

This works for me:

cd X
find ./ -iname "*.xlsx" > /tmp/out
SAVEIFS=$IFS;
IFS=$(echo -en "\n\b");
while read line ;
do
   cd $(dirname $line);
   libreoffice --headless --convert-to xls $(basename $line);
   echo $PWD;
   cd -;
done < /tmp/out;
IFS=$SAVEIFS
David Foerster
  • 36,890
  • 56
  • 97
  • 151
Nehal J Wani
  • 463
  • 3
  • 13
3

Here is a python script that does as you described.

For convenience reasons, to be used with other conversion commands, I defined the filepath+name and the destination before entering it in the convert command. That also makes it easy to change the destination to something else than the file's current directory (if for some reason you might need that).

note: In some cases (like mine), the command

libreoffice --headless --convert-to xls

only works when using sudo. If that is the case, you need to change ownership of ~/.config with the command:

sudo chown -R --reference="$HOME" ~/.config

as described here.

The script:

#!/usr/bin/python3

convert_dir = "/path/to/folder/tobeconverted"
import os
import subprocess

for root, dirs, files in os.walk(convert_dir):
    for name in files:
        if name.endswith(".xlsx"):
            # filepath+name
            file = root+"/"+name
            destination = root
            subprocess.Popen(["libreoffice", "--headless", "--convert-to", "xls", file, "--outdir", destination])
        else:
            pass

Copy it into an empty textfile, replace the directory in the top of the file, save it with the .py extension and run it with the command:

python3 /path/to/scrip/script.py

But I am pretty sure you know that. :)

Jacob Vlijm
  • 85,475