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.

1
  • 2
    If you search join you'll find plenty of similar questions. Commented Oct 14, 2016 at 12:09

1 Answer 1

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
0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.