Grep multiple strings from text file

前端 未结 3 489
没有蜡笔的小新
没有蜡笔的小新 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: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/*

提交回复
热议问题