简体   繁体   中英

How to place all text from a file into the search pattern of grep?

I am using grep like this:

grep '^[abcd]*$' file.txt

I have a file, list.txt , containing a list like this:

potato
orange
carrot

How can I send all of the lines from list.txt to inside the search pattern of grep , the equivalent of typing this:

grep '^[potatoorangecarrot]*$' file.txt

All of the lines in list.txt are put together and sent to grep as one long search.

How can I place all of the text from a file into the search pattern of grep?

Like this:

string="^[$(tr -d '\n' < list.txt)]*$"
echo $string

Then

grep "$string" file.txt

The $() bit says " take the output of running the command within its parentheses ". The tr command says to delete ( -d ) all linefeeds from file list.txt .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM