cjjia
V2EX  ›  问与答

想要一个处理txt文档的工具或者办法

  •  
  •   cjjia · Jul 11, 2012 · 4864 views
    This topic created in 5239 days ago, the information mentioned may be changed or developed.
    比如我有1.txt和2.txt两个文档,他们的内容都是一行一行的,有上万行。

    现在我要把1.txt和2.txt进行对比,如果1.txt里面存在192.168.0.1这一行,就搜索2.txt里面存不存在192.168.0.1这一行,如果存在则将其删除。

    就是说把所以1.txt里面存在的内容,将其在2.txt里面删除。

    不知道有没有现成的工具,或者其他软件能曲线实现这个功能,谢谢了。
    13 replies  •  1970-01-01 08:00:00 +08:00
    cosbeta
    cosbeta
    Jul 11, 2012❤️2
    1
    <?php
    $a = file( "1.txt" );
    $b = file_get_contents("2.txt");
    foreach( $a as $line){

    $line = trim($line);
    if( strlen( $line) <1) continue;
    if( substr_count($b,$line) >0) $b = str_replace($line,"",$b);

    }?>

    php代码如上,哈哈,程序没考虑效率,如果文件很大,就会很消耗内存
    lululau
    lululau
    Jul 11, 2012
    2
    grep -vFf 1.txt 2.txt
    cjjia
    cjjia
    OP
    Jul 11, 2012
    3
    @cosbeta 不知道这个怎么用,是把上面的代码放到index.php文档里面,然后上传到php空间吗?然后把1.txt和2.txt上传到同一目录?

    在浏览器打开之后没显示什么,然后下载回来1.txt和2.txt看了一下里面内容没变,是不是服务器缺少什么函数?

    可以加下QQ吗? 如果你帮我解决了 可以适当的付些报酬给你
    cosbeta
    cosbeta
    Jul 11, 2012
    4
    你把两个文件email给我就是 china.cos 在gmaill
    @lululau 的方法匹配太泛了,会误删的呢
    cosbeta
    cosbeta
    Jul 11, 2012
    5
    首先,1.txt和2.txt的权限要对,然后 和php放在同一个目录。 直接运行 php tool.php 假设php文件名是tool.php
    reus
    reus
    Jul 11, 2012
    6
    sort 2.txt 1.txt 1.txt | uniq -u
    forsaken
    forsaken
    Jul 11, 2012
    7
    只能是开发语言来实现,比如php或者ruby或者C吧。软件貌似很少。
    shiny
    shiny
    Jul 11, 2012❤️1
    8
    <?php
    $a = explode("\n",file_get_contents("1.txt"));
    $b = explode("\n",file_get_contents("2.txt"));
    $c = array_diff($b,$a);
    file_put_contents("3.txt",implode("\n",$c));
    4BVL25L90W260T9U
    4BVL25L90W260T9U
    Jul 11, 2012
    9
    #!/usr/bin/env python
    #coding:utf-8

    file_a = open('1.txt', 'r').readlines()
    file_b = open('2.txt', 'r').readlines()
    new_b = [lb for lb in file_b if lb not in file_a]#遍历2中每一行,看是否在1中存在
    with open('new_2.txt', 'w') as new_file:
    for l in new_b:
    new_file.write(l)
    bullda
    bullda
    Jul 11, 2012
    10
    beyond compare?
    cjjia
    cjjia
    OP
    Jul 11, 2012
    11
    @shiny 谢谢,真的很感谢。代码能用
    HowardMei
    HowardMei
    Jul 11, 2012
    12
    文件所在目录terminal输入:
    awk ' !x[$0]++' 1.txt 2.txt | split -l $(awk 'END { print NR }' 1.txt)
    得到两个新文件,其中一个就是去重后的2.txt
    从服务器bash_proile中拿来的,会用awk的同学应该很容易理解。
    cosbeta
    cosbeta
    Jul 11, 2012
    13
    @HowardMei awk确实是最方便的
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2091 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 47ms · UTC 07:32 · PVG 15:32 · LAX 23:32 · JFK 02:32
    ♥ Do have faith in what you're doing.