【问题标题】:Extract strings in a text file using grep使用 grep 提取文本文件中的字符串
【发布时间】:2013-06-21 21:49:09
【问题描述】:

我有 file.txt,每行一个名称,如下所示:

ABCB8
ABCC12
ABCC3
ABCC4
AHR
ALDH4A1
ALDH5A1
....

我想从一个 input.txt 文件中对其中的每一个进行 grep。

我手动一次做一个

grep "ABCB8" input.txt > output.txt

有人可以帮助自动从 input.txt grep file.txt 中的所有字符串并将其写入 output.txt。

【问题讨论】:

    标签: string shell grep string-matching


    【解决方案1】:

    您可以使用-f 标志,如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
    

    标志

    • -f FILE--file=FILE

    从 FILE 中获取模式,每行一个。空文件 包含零个模式,因此不匹配。 (-f 是 由 POSIX 指定。)

    • -o--only-matching

    仅打印匹配行的匹配(非空)部分,使用 每个这样的部分都在单独的输出行上。

    【讨论】:

    • 我从 file.txt 获得了带有突出显示行的 input.txt 文件
    • 尝试不使用> output.txt。请注意,file.txt 包含模式文件列表,input.txt 是要查看的文件。
    【解决方案2】:
    for line in `cat text.txt`; do grep $line input.txt >> output.txt; done
    

    text.txt的内容:

    ABCB8
    ABCC12
    ABCC3
    ABCC4
    AHR
    ALDH4A1
    ALDH5A1
    

    编辑

    使用 while read 的更安全的解决方案:

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

    编辑 2

    示例text.txt:

    ABCB8
    ABCB8XY
    ABCC12
    

    示例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
    

    如果您不关心行的顺序,快速的解决方法是通过sort | uniq 传递解决方案:

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

    然后结果在output.txt中。

    编辑 3

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

    这样好吗?

    【讨论】:

    • for 循环不是解决此问题的正确工具,请阅读Why you don't read lines with "for"。加上grep 已经在输入文件上循环。
    • @EdouardLopez:我知道,但在这个简单的例子中并不重要。无论如何,我在使用 while read 时从来没有遇到过任何麻烦。
    • 你传播不良做法,你 while/for 没用,你试图模仿行为或 grep(循环文件的每一行)将它们传递给...... grep。跨度>
    • 请更清楚地说明您的方法:创建一个包含模式列表的第二个文件,将其用作grep 的输入。这也很尴尬,因为您的方法所基于的文件是 @user1779730 正在寻找的结果。因此,您的解决方案基于自身(无限循环:S)
    • @EdouardLopez:我认为 grep 的字符串是 text.txt 中的字符串。据我了解,OP - 它要求一个循环。
    猜你喜欢
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    • 2021-02-27
    • 2023-04-04
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    相关资源
    最近更新 更多