Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Merging two files by a column and add 0 when entry is missing

I have two files as below.

  • File1
    There are five countries in File1

    >USA
    >England
    >France
    >Japan
    >Thailand

  • File2
    There are only four in File2

    >USA
    >England
    >Japan
    >Thailand

I use paste -d "," file1.txt file2.txt1 to merge the two files together

  • output

    >USA ,>USA
    >England,>England
    >France,>Japan
    >Japan,>Thailand
    >Thailand,

As you can see here, the order of the list from the two files for the output doesn’t align with each other because one value is missing in File2 -France. Instead, it shifts and changes after the 3rd row -"France"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

-Desire output


    >USA       >USA
    >England   >England
    >France    >0 (or any symbols)
    >Japan     >Japan
    >Thailand  >Thailand  

    

How can I write a UNIX command statement that replaces 0 or any symbols @#$%>|:" etc for the missing values,but the remaining order stay matched with each other? What need to be added, changed, or modified for the paste -d "," file1.txt file2.txt1

Any help would be highly appreciated. Thank you.

>Solution :

With your shown samples and attempts please try following awk solution. Using awk + column combination here. You need to pass file2 and file1 respectively files into it and we should be Good to go here. For lines missing in file1 are having >0 you can change it as per your requirement too as mentioned in your question.

awk '
BEGIN{ OFS="\t" }
FNR==NR{
  arr[$0]
  next
}
{
  print (($0 in arr)?$0 OFS $0:$0 OFS ">0")
}
' file2 file1 | column -t -s $'\t'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading