Bash 在.odt文件列表中查找字符串并打印匹配行

Bash 在.odt文件列表中查找字符串并打印匹配行,bash,Bash,我正试图找到一种方法,在odt文件列表中找到一个单词。我是指odt文件中的一个词。 然后,我想看看哪些文件包含这个单词和匹配这个单词的行(或者至少是它前面的一些单词和它后面的一些单词) 以下是我到目前为止的情况: for file in *.odt; do unzip -c "$file" | grep -iq "searched_word" && echo "$file"; done 这将显示包含我要查找的单词的文件的名称: filename1.odt filename2.o

我正试图找到一种方法,在odt文件列表中找到一个单词。我是指odt文件中的一个词。 然后,我想看看哪些文件包含这个单词和匹配这个单词的行(或者至少是它前面的一些单词和它后面的一些单词)

以下是我到目前为止的情况:

for file in *.odt; do unzip -c "$file" | grep -iq "searched_word" && echo "$file"; done
这将显示包含我要查找的单词的文件的名称:

filename1.odt
filename2.odt
但是,我无法在文件中看到与单词匹配的行,例如:

the is the first line with searched_word blabla : /path/filename1.odt
the is the second line with searched_word blabla : /path/filename2.odt

有什么想法吗?

一种方法是让grep打印您的文件名,即使您正在使用stdin。有以下几种选择:

   -H, --with-filename
          Print the file name for each match.  This is the default when there is more than one file to search.

   --label=LABEL
          Display input actually coming from standard input as input coming from file LABEL.  This is especially useful when implementing tools like zgrep, e.g., gzip -cd foo.gz |  grep  --label=foo  -H
          something.  See also the -H option.

   -n, --line-number
          Prefix each line of output with the 1-based line number within its input file.

   -a, --text
          Process a binary file as if it were text; this is equivalent to the --binary-files=text option.
因此,只需设置
--label=$file-Ha-n
,就可以得到输出,就好像grep是直接运行的一样

你需要-H。。。容易出错,但如果没有它,则“只有一个输入文件”,因此不会打印标签

如果grep的启发式算法决定输入看起来像二进制的,那么您可能需要-a


事实上,你为什么不能直接运行grep?某些grep安装会自动解包.gz文件。

将grep输出读入一个变量,并使用相同的语句回显它

grep-i“搜索单词”|读取x&&echo“$x:$file”

阴性病例

$ for file in *.odt; do ; cat $file  | grep -i "QQQQQ" | read x && echo "$x:$file" ; done
$

Java 1.8中的基本实现:

package app;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.filter.Filters;
import org.jdom2.input.SAXBuilder;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;


/**
 *  OfficeSearch
 */
public class OfficeSearch
{
    private final Set<String> searchSet = new HashSet<>();
    private static OfficeSearch INSTANCE = new OfficeSearch();

    //
    // main
    //
    public static void main(String[] args) {
        INSTANCE.execute(args);
    }

    //
    //  execute
    //
    private void execute(String[] args) {
        if (args.length > 1) {
            for (int i=1; i<args.length; i++) {
                searchSet.add(args[i].toLowerCase());
            }
            try {
                Files.list(Paths.get(args[0])).sorted().
                    map(Path::toFile).
                    filter(this::is_odt).
                    forEach(this::search);
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
        else {
            System.out.println("Usage: OfficeSearch <directory> <search_term> [...]");
        }

    }

    //
    //  is_odt
    //
    private boolean is_odt(File file) {
        if (file.isFile()) {
            final String name = file.getName();
            final int dotidx = name.lastIndexOf('.');
            if ((0 <= dotidx) && (dotidx < name.length() - 1)) {
                return name.substring(dotidx + 1).equalsIgnoreCase("odt");
            }
        }
        return false;
    }

    //
    // search
    //
    private void search(File odt) {
        try (ZipFile zip = new ZipFile(odt)) {
            final ZipEntry content = zip.getEntry("content.xml");
            if (content != null) {
                final SAXBuilder builder = new SAXBuilder();
                final Document doc = builder.build(zip.getInputStream(content));
                final Element root = doc.getRootElement();
                final Namespace office_ns = root.getNamespace("office");
                final Namespace text_ns = root.getNamespace("text");
                final Element body = root.getChild("body", office_ns);
                if (body != null) {
                    boolean found = false;
                    for (Element e : body.getDescendants(Filters.element(text_ns))) {
                        if ("p".equals(e.getName()) ||
                            "h".equals(e.getName())) {
                            final String s = e.getValue().toLowerCase();
                            for (String p : searchSet) {
                                if (s.contains(p)) {
                                    if (!found) {
                                        found = true;
                                        System.out.println("\n" + odt.toString());
                                    }
                                    System.out.println(e.getValue());
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (IOException | JDOMException e) {
            e.printStackTrace();
        }
    }

}
package应用程序;
导入org.jdom2.Document;
导入org.jdom2.Element;
导入org.jdom2.JDOMException;
导入org.jdom2.Namespace;
导入org.jdom2.filter.Filters;
导入org.jdom2.input.SAXBuilder;
导入java.io.File;
导入java.io.IOException;
导入java.nio.file.Files;
导入java.nio.file.Path;
导入java.nio.file.path;
导入java.util.HashSet;
导入java.util.Set;
导入java.util.zip.ZipEntry;
导入java.util.zip.ZipFile;
/**
*办公室研究
*/
公共类办公室研究
{
私有最终集searchSet=newhashset();
private static OfficeSearch INSTANCE=new OfficeSearch();
//
//主要
//
公共静态void main(字符串[]args){
execute(args);
}
//
//执行
//
私有void execute(字符串[]args){
如果(参数长度>1){

for(int i=1;我同意你的想法,不幸的是.odt文件是压缩的,所以cat不能使用它。它必须先解压缩,这就是为什么我在我建议的命令中编写了
do unzip-c“$file”
for file in*.odt;do;cat$file | grep-i“qqqq”| read x&&echo“$x:$file”;done
给出:
:filename1.odt:filename2.odt
是的..对,但是你可以调整你的语句,也就是说你可以将
grep-iq“searched_word”和&echo“$file”
替换为
grep-iq“searched_word”| read x&&echo“$x:$file”
,对于*.odt中的文件,它将不可调谐地工作
“Schengen”| read x&&echo“$x:$file”done
没有给出任何结果。谢谢你的回答,但这不起作用。以下是我在*.odt;do unzip-c“$file”| grep-iq--label=“$file”searched_word“&&echo“$file”done
中尝试的
-H
…很容易出错,但没有它就没有了”只有1个输入文件"所以没有打印标签。你的
-q
?-q,-quiet,--silent抑制所有正常输出如果文件内容是文本,那么解压后就不应该出现。如果它不是zip中的文本,我看不出你曾期望它如何工作?你可以添加
-a
,将二进制文件视为文本。这一切都在
man grep 事实上,昨天我看到了同样的问题——我认为是有效文本的管道输出,grep决定是二进制的。
-a
很好地解决了这个问题。
package app;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.filter.Filters;
import org.jdom2.input.SAXBuilder;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;


/**
 *  OfficeSearch
 */
public class OfficeSearch
{
    private final Set<String> searchSet = new HashSet<>();
    private static OfficeSearch INSTANCE = new OfficeSearch();

    //
    // main
    //
    public static void main(String[] args) {
        INSTANCE.execute(args);
    }

    //
    //  execute
    //
    private void execute(String[] args) {
        if (args.length > 1) {
            for (int i=1; i<args.length; i++) {
                searchSet.add(args[i].toLowerCase());
            }
            try {
                Files.list(Paths.get(args[0])).sorted().
                    map(Path::toFile).
                    filter(this::is_odt).
                    forEach(this::search);
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
        else {
            System.out.println("Usage: OfficeSearch <directory> <search_term> [...]");
        }

    }

    //
    //  is_odt
    //
    private boolean is_odt(File file) {
        if (file.isFile()) {
            final String name = file.getName();
            final int dotidx = name.lastIndexOf('.');
            if ((0 <= dotidx) && (dotidx < name.length() - 1)) {
                return name.substring(dotidx + 1).equalsIgnoreCase("odt");
            }
        }
        return false;
    }

    //
    // search
    //
    private void search(File odt) {
        try (ZipFile zip = new ZipFile(odt)) {
            final ZipEntry content = zip.getEntry("content.xml");
            if (content != null) {
                final SAXBuilder builder = new SAXBuilder();
                final Document doc = builder.build(zip.getInputStream(content));
                final Element root = doc.getRootElement();
                final Namespace office_ns = root.getNamespace("office");
                final Namespace text_ns = root.getNamespace("text");
                final Element body = root.getChild("body", office_ns);
                if (body != null) {
                    boolean found = false;
                    for (Element e : body.getDescendants(Filters.element(text_ns))) {
                        if ("p".equals(e.getName()) ||
                            "h".equals(e.getName())) {
                            final String s = e.getValue().toLowerCase();
                            for (String p : searchSet) {
                                if (s.contains(p)) {
                                    if (!found) {
                                        found = true;
                                        System.out.println("\n" + odt.toString());
                                    }
                                    System.out.println(e.getValue());
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (IOException | JDOMException e) {
            e.printStackTrace();
        }
    }

}