【问题标题】:How to select different lines by bash,pipe?如何通过 bash,pipe 选择不同的行?
【发布时间】:2013-07-30 11:21:02
【问题描述】:

我的任务
我有一个包含以下内容的文件 A.txt。

aijdish uhuih
buh iiu hhuih
zhuh hiu
d uhiuhg ui
...

我想选择带有这些单词的行 aijdish, d, buh ... 我只知道我可以:

cat A.txt | grep "aijdish" > temp.txt
cat A.txt | grep "d" >> temp.txt
cat A.txt | grep "buh" >> temp.txt
...

但是我这次有几千字需要选择,在bash下怎么做呢?

【问题讨论】:

    标签: bash grep pipe


    【解决方案1】:

    由于您要查找的单词很多,我建议将模式放入文件中并使用 greps -f 选项:

    $ cat grep-pattern.txt
    aijdish
    buh
    d
    
    $ grep -f grep-pattern.txt inputfile
    aijdish uhuih
    buh iiu hhuih
    d uhiuhg ui
    

    但如果您有像 d 这样的词,您可能需要添加 -w 选项以仅匹配整个词而不是部分词。

    grep -wf grep-pattern.txt inputfile
    

    【讨论】:

    • 鉴于模式中存在d,将-w 添加到grep 调用中可能是个好主意。
    【解决方案2】:
    $ grep -E "aijdish|d|buh" inputfile
    aijdish uhuih
    buh iiu hhuih
    d uhiuhg ui
    

    【讨论】:

    • 谢谢,但当我有几千个不同的单词时,这不太适用
    【解决方案3】:

    将要搜索的单词存储在一个文件中(比如 a.txt),然后编写一个脚本来搜索 a.txt 中的每一行并在所需文件中进行匹配

    【讨论】:

    • 我知道,但我想学习如何仅使用 bash 来完成。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 2011-10-18
    • 1970-01-01
    相关资源
    最近更新 更多