【问题标题】:Linux command to grab lines similar between filesLinux命令在文件之间抓取相似的行
【发布时间】:2014-08-11 05:11:05
【问题描述】:

我有一个文件,每行一个单词。

我有第二个文件,每行有很多单词。

我想浏览第一个文件中的每一行,以及在第二个文件中找到的所有行,我想将这些行从第二个文件复制到新的第三个文件中。

有没有办法简单地使用 Linux 命令来做到这一点?

编辑:感谢您的输入。但是,我应该更好地说明:

第一个文件只是一个数字列表(每行一个数字)。

463463 43454 33634

第二个文件非常混乱,我只是在寻找以任何方式排列的数字字符串(不需要单个单词)。所以,例如

ewjleji jejeti ciwlt 463463.52%

会返回一个命中。我认为在这种情况下向我建议的内容不起作用(请原谅我因为不够详细而不得不进行编辑)

【问题讨论】:

标签: linux


【解决方案1】:

如果n是你的第一个文件的行数,m是你的第二个文件的行数,那么你可以在O(nm)时间内通过以下方式解决这个问题:

cat firstfile | while read word; do
    grep "$word" secondfile >>thirdfile
done

如果您需要比这更有效地解决它,我认为没有任何内置实用程序可以解决此问题。

至于您的编辑,此方法确实按照您描述的方式工作。

【讨论】:

    【解决方案2】:

    这是一个简短的脚本。 需要 3 个命令行参数 1- 文件,每行 1 个单词,2- 文件,每个单词要匹配多行在 file1 和 3- 你的输出文件中:

    #!/bin/bash
    
    ## test input and show usage on error
    test -n "$1" && test -n "$2" && test -n "$3" || {
        printf "Error: insufficient input, usage: %s file1 file2 file3\n" "${0//*\//}"
        exit 1
    }
    
    while read line || test -n "$line" ; do
    
        grep "$line" "$2" 1>>"$3" 2>/dev/null
    
    done <"$1"
    

    示例:

    $ cat words.txt
    me
    you
    them
    
    $ cat lines.txt
    This line is for me
    another line for me
    maybe another for me
    one for you
    another for you
    some for them
    another for them
    here is one that doesn't match any
    
    $ bash ../lines.sh words.txt lines.txt outfile.txt
    
    $ cat outfile.txt
    This line is for me
    another line for me
    maybe another for me
    some for them
    one for you
    another for you
    some for them
    another for them
    

    (是的,我知道 me 也与示例文件中的 some 匹配,但这并不是重点。

    【讨论】:

      猜你喜欢
      • 2013-07-24
      • 2018-08-05
      • 2015-02-19
      • 1970-01-01
      • 1970-01-01
      • 2012-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多