【问题标题】:Merge two lines with grep or sed用 grep 或 sed 合并两行
【发布时间】:2013-07-07 00:00:20
【问题描述】:

我有这样一个问题:我有两个带密钥的文件:

file1: aa, bb, cc, dd, ee, ff, gg;

file2: aa, bb, cc, zz, yy, ww, oo;

我需要使用 grep/sed 编写一个脚本来生成两个文件:

res1.txt - will contain similar keys from both files: aa, bb, cc;

res2.txt - will contain ONLY keys from file2 which differs from files1: zz, yy, ww, oo.

我可以使用这些工具来完成这项工作吗?我如何或需要使用 python 脚本来完成这项工作?谢谢。

我正在使用 Windows。

【问题讨论】:

    标签: python regex windows sed grep


    【解决方案1】:

    您可以使用comm 显示常用行,但您必须对文件进行排序(并通过tr 将它们转换为每行键 格式):

    comm -12 <(tr -s ' ,' '\n' < file1 | sort) <(tr -s ' ,' '\n' < file2 | sort)
    comm -13 <(tr -s ' ,' '\n' < file1 | sort) <(tr -s ' ,' '\n' < file2 | sort)
    

    【讨论】:

    • 什么是通讯?我在 Windows 电脑上
    • @yozhik - 在您的问题中提及您的窗口会很有用。当您在所需的解决方案中命名 2 个传统的 UNIX 工具时,我们可以合理地假设您使用的是 UNIX。
    【解决方案2】:

    每个 UNIX 安装附带的通用文本处理工具被命名为 awk

    awk -F', *|;' '
    NR==FNR { for (i=1; i<NF;i++) file1[$i]; next }
    {
        for (i=1; i<NF; i++) {
            sfx = ($i in file1 ? 1 : 2)
            printf "%s%s", sep[sfx], $i > ("res" sfx ".txt")
            sep[sfx]=", "
        }
    }
    END { for (sfx in sep) print ";" > ("res" sfx ".txt") }
    ' file1 file2
    

    【讨论】:

      【解决方案3】:

      在 Python 中,您可以执行以下操作。

      string1 = "aa, bb, cc, dd, ee, ff, gg;"
      string2 = "aa, bb, cc, zz, yy, ww, oo;"
      
      list1 = string1.rstrip(';').split(', ')
      list2 = string2.rstrip(';').split(', ')
      
      common_words = filter(lambda x: x in list1, list2)
      unique_words = filter(lambda x: x not in list1, list2)
      
      >>> common_words
      ['aa', 'bb', 'cc']
      >>> unique_words
      ['zz', 'yy', 'ww', 'oo']
      

      然后,您可以根据需要将这些写入文件。

      例如:

      common_string = ', '.join(common_words) + ';'
      with open("common.txt", 'w') as common_file:
          common_file.write(common_string)
      

      【讨论】:

        【解决方案4】:

        GNU 的丑陋工作:

        sed -r 's#(\w+)[,;]\s*#/\1/{x;s/.*/\&\1,/;x};#g;s#.*#&x;s/,$/;/#' file1|sed -rf - file2 > res1.txt
        sed -r 's#(\w+),\s#\1[,;]\\s*|#g;s#(.*);#s/\1//g#' file1|sed -rf - file2 > res2.txt
        

        $猫文件1文件2 aa、bb、cc、dd、ee、ff、gg; aa、bb、cc、zz、yy、ww、oo; $ sed -r 's#(\w+)[,;]\s*#/\1/{x;s/.*/\&\1,/;x};#g;s#.*#&x ;s/,$/;/#' 文件1|sed -rf - 文件2 aa,bb,cc; $ sed -r 's#(\w+),\s#\1[,;]\\s*|#g;s#(.*);#s/\1//g#' file1|sed -rf - 文件2 zz, yy, ww, oo;

        引用Windows:

        sed -r "s#(\w+)[,;]\s*#/\1/{x;s/.*/\&\1,/;x};#g;s#.*#&x;s/,$/;/#" file1|sed -rf - file2 > res1.txt
        sed -r "s#(\w+),\s#\1[,;]\\s*|#g;s#(.*);#s/\1//g#" file1|sed -rf - file2 > res2.txt
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-02-21
          • 2020-09-22
          • 1970-01-01
          • 2013-09-09
          • 2015-07-11
          • 2022-09-27
          • 1970-01-01
          相关资源
          最近更新 更多