Compare 2 files and remove any lines in file2 when they match values found in file1

前端 未结 4 675
死守一世寂寞
死守一世寂寞 2020-12-10 22:11

I have two files. i am trying to remove any lines in file2 when they match values found in file1. One file has a listing like so:

File1

ZNI008
ZNI009         


        
相关标签:
4条回答
  • 2020-12-10 22:45

    I like the grep solution from byrondrossos better, but here's another option:

    sed $(awk '{printf("-e /%s/d ", $1)}' file1) file2 > file3
    
    0 讨论(0)
  • 2020-12-10 22:46

    What about:

    grep -F -v -f file1 file2 > file3
    
    0 讨论(0)
  • 2020-12-10 22:48

    this is using Bash and GNU sed because of the -i switch

    cp file2 file3
    while read -r; do
        sed -i "/$REPLY/d" file3
    done < file1
    

    there is surely a better way but here's a hack around -i :D

    cp file2 file3
    while read -r; do
        (rm file3; sed "/$REPLY/d" > file3) < file3
    done < file1
    

    this exploits shell evaluation order


    alright, I guess the correct way with this idea is using ed. This should be POSIX too.

    cp file2 file3
    while read -r line; do
        ed file3 <<EOF
    /$line/d
    wq
    EOF
    done < file1
    

    in any case, grep seems to do be the right tool for the job.
    @byrondrossos answer should work for you well ;)

    0 讨论(0)
  • 2020-12-10 23:05

    This is admittedly ugly but it does work. However, the path must be the same for all of the (except of course the ZNI### portion). All but the ZNI### of the path is removed so the command grep -vf can run correctly on the sorted files.

    First Convert "testfile2" to "testfileconverted" to just show the ZNI###

    cat /testfile2 | sed 's:^.*_ZNI:ZNI:g' | sed 's:_.*::g' > /testfileconverted
    

    Second use inverse grep of the converted file compared to the "testfile1" and add the reformatted output to "testfile3"

    bash -c 'grep -vf <(sort /testfileconverted) <(sort /testfile1)' | sed "s:^:\copy /Y \\\|server\\\foldername\\\version\\\20050001_:g" | sed "s:$:_162635\.xml \\\|server\\\foldername\\\version\\\folder\\\:g" | sed "s:|:\\\:g" > /testfile3
    
    0 讨论(0)
提交回复
热议问题