Sunday, November 11, 2012

Find string from list of ODT files in Linux

In Linux, a string pattern can be searched using grep command from one or more files from a directory (including its sub directories). Normally the search will be easy when in the case of text files including program source code files like c, PHP, Java and etc. At the same time a search from list of ODT files from a directory is not that easy.

This can be also possible with the use of utility command such as find, unzip and grep. The below code will done the job perfectly. The parameter can be changed upon your wish. This program will output file name(s) which contains the search string.

#content of searchodt.sh

#!/bin/bash

if [ $# -ne 1 ]; then
    echo "Usage: sh searchodt.sh <searchterm>"
    exit 1
fi

for file in $(find . -name "*.odt" -type f); do
    unzip -ca "$file" content.xml | grep -qil "$1"
    if [ $? -eq 0 ]; then
        echo "$file"
    fi
Done

No comments:

Post a Comment