Inner join on two text files

前端 未结 5 2046
陌清茗
陌清茗 2020-11-22 05:06

Looking to perform an inner join on two different text files. Basically I\'m looking for the inner join equivalent of the GNU join program. Does such a thing exist? If not,

相关标签:
5条回答
  • 2020-11-22 05:36

    Should not the file2 contain LUA at the end?

    If yes, you can still use join:

    join -t'|' -12 <(sort -t'|' -k2 file1) file2
    
    0 讨论(0)
  • 2020-11-22 05:42

    You may modify this script:

    cat file2 | while read line; do
        grep $line file1 # or whatever you want to do with the $line variable
    done
    

    while loop reads file2 line by line and gives that line to the grep command that greps that line in file1. There're some extra output that maybe removed with grep options.

    0 讨论(0)
  • 2020-11-22 05:46

    Looks like you just need

    grep -F -f file2 file1
    
    0 讨论(0)
  • 2020-11-22 06:02

    Here's an awk option, so you can avoid the bash dependency (for portability):

    $ awk -F'|' 'NR==FNR{check[$0];next} $2 in check' file2 file1
    

    How does this work?

    • -F'|' -- sets the field separator
    • 'NR==FNR{check[$0];next} -- if the total record number matches the file record number (i.e. we're reading the first file provided), then we populate an array and continue.
    • $2 in check -- If the second field was mentioned in the array we created, print the line (which is the default action if no actions are provided).
    • file2 file1 -- the files. Order is important due to the NR==FNR construct.
    0 讨论(0)
  • 2020-11-22 06:02

    You can use paste command to combine file :

    paste [option] source files [>destination file]
    

    for your example it would be

    paste file1.txt file2.txt >result.txt
    
    0 讨论(0)
提交回复
热议问题