Grep multiple strings from text file

前端 未结 3 488
没有蜡笔的小新
没有蜡笔的小新 2021-01-19 00:39

Okay so I have a textfile containing multiple strings, example of this -

Hello123
Halo123
Gracias
Thank you
...

I want grep to use these st

相关标签:
3条回答
  • 2021-01-19 01:09

    With GNU grep:

    grep -f file1 file2
    

    -f FILE: Obtain patterns from FILE, one per line.

    Output:

    123-example-Halo123
    321-example-Gracias-com-no
    
    0 讨论(0)
  • 2021-01-19 01:24

    You should probably look at the manpage for grep to get a better understanding of what options are supported by the grep utility. However, there a number of ways to achieve what you're trying to accomplish. Here's one approach:

    grep -e "Hello123" -e "Halo123" -e "Gracias" -e "Thank you" list_of_files_to_search
    

    However, since your search strings are already in a separate file, you would probably want to use this approach:

    grep -f patternFile list_of_files_to_search
    
    0 讨论(0)
  • 2021-01-19 01:33

    I can think of two possible solutions for your question:

    1. Use multiple regular expressions - a regular expression for each word you want to find, for example:

      grep -e Hello123 -e Halo123 file_to_search.txt
      
    2. Use a single regular expression with an "or" operator. Using Perl regular expressions, it will look like the following:

      grep -P "Hello123|Halo123" file_to_search.txt
      

    EDIT: As you mentioned in your comment, you want to use a list of words to find from a file and search in a full directory.

    You can manipulate the words-to-find file to look like -e flags concatenation:

    cat words_to_find.txt | sed 's/^/-e "/;s/$/"/' | tr '\n' ' '
    

    This will return something like -e "Hello123" -e "Halo123" -e "Gracias" -e" Thank you", which you can then pass to grep using xargs:

    cat words_to_find.txt | sed 's/^/-e "/;s/$/"/' | tr '\n' ' ' | dir_to_search/*
    

    As you can see, the last command also searches in all of the files in the directory.

    SECOND EDIT: as PesaThe mentioned, the following command would do this in a much more simple and elegant way:

    grep -f words_to_find.txt dir_to_search/*

    0 讨论(0)
提交回复
热议问题