Extract strings in a text file using grep

2019-08-23 09:49发布

I have file.txt with names one per line as shown below:

ABCB8
ABCC12
ABCC3
ABCC4
AHR
ALDH4A1
ALDH5A1
....

I want to grep each of these from an input.txt file.

Manually i do this one at a time as

grep "ABCB8" input.txt > output.txt

Could someone help to automatically grep all the strings in file.txt from input.txt and write it to output.txt.

2条回答
Luminary・发光体
2楼-- · 2019-08-23 10:46
for line in `cat text.txt`; do grep $line input.txt >> output.txt; done

Contents of text.txt:

ABCB8
ABCC12
ABCC3
ABCC4
AHR
ALDH4A1
ALDH5A1

Edit:

A safer solution with while read:

cat text.txt | while read line; do grep "$line" input.txt >> output.txt; done

Edit 2:

Sample text.txt:

ABCB8
ABCB8XY
ABCC12

Sample input.txt:

You were hired to do a job; we expect you to do it.
You were hired because ABCB8 you kick ass;
we expect you to kick ass.
ABCB8XY You were hired because you can commit to a rational deadline and meet it;
ABCC12 we'll expect you to do that too.
You're not someone who needs a middle manager tracking your mouse clicks

If You don't care about the order of lines, the quick workaround would be to pipe the solution through a sort | uniq:

cat text.txt | while read line; do grep "$line" input.txt >> output.txt; done; cat output.txt | sort | uniq > output2.txt

The result is then in output.txt.

Edit 3:

 cat text.txt | while read line; do grep "\<${line}\>" input.txt >> output.txt; done

Is that fine?

查看更多
做个烂人
3楼-- · 2019-08-23 10:49

You can use the -f flag as described in Bash, Linux, Need to remove lines from one file based on matching content from another file

grep -o -f file.txt input.txt > output.txt

Flag

  • -f FILE, --file=FILE:

Obtain patterns from FILE, one per line. The empty file contains zero patterns, and therefore matches nothing. (-f is specified by POSIX.)

  • -o, --only-matching:

Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

查看更多
登录 后发表回答