1

I have two files each containing a timestamp and a count as follows

File1.txt

   9 2016-06-22
   3 2016-06-23
   2 2016-06-24
   1 2016-06-25
   2 2016-06-26
   2 2016-06-27

File2.txt

   3 2016-06-23
   2 2016-06-25
   5 2016-06-27

I would like to created an output where it uses the date column (col-3) in both the files and create an joined output which is as follows.

Expected result:

   9   2016-06-22
   3 3 2016-06-23
   2   2016-06-24
   1 2 2016-06-25
   2   2016-06-26
   2 5 2016-06-27

Using paste command is very complex and involves manual effort to get the expected output.Can someone help me with this ?

Thank you.

  • 2
    If you search join you'll find plenty of similar questions. – don_crissti Oct 14 '16 at 12:09
2

The best solution is to use the join command:

join -j 2 -a 1 -e " " -o 1.1 2.1 1.2 File1.txt File2.txt

Not the more elegant solution, but if you want to learn shell-script this should do the job:

while read line1; do
    file1_number=$(echo ${line1} | cut -d ' ' -f 1)
    file1_date=$(echo ${line1} | cut -d ' ' -f 2)
    line2=$(grep ${file1_date} File2.txt)
    file2_number=$(echo ${line2} | cut -d ' ' -f 1)
    if [[ -z "${file2_number}" ]]; then
        file2_number=" "
    fi
    echo ${file1_number} "${file2_number}" ${file1_date}
done < File1.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.