0

I need to compare below 2 files.

The head_file:

    2345;int builder(
    1000;char type::edit::display <test>(
    250;void unamed_string_tree*

The ref_file:

    2000;int builder(
    500;char type::edit::display <test>(
    3000;fillTest*(

Desired output:

FUNCTION,HEAD,REF,DIFF
int builder(,2345,2000,-345
char type::edit::display <test>(,1000,500,-500
void unamed_string_tree*,250,0,-250
fillTest*(,0,3000,3000
  • where does the "-245" cames from? What have you tried? – JJoao Sep 25 '15 at 17:14
  • 2
    @JJoao I think it's a typo, I is meant -345... – chaos Sep 25 '15 at 17:21
2

With awk:

awk -F";" 'BEGIN{OFS=",";
  print "FUNCTION,HEAD,REF,DIFF"}
  FNR==NR{a[$2]=$1;next}
  {print $2,$1,a[$2]*1,a[$2]-$1; delete a[$2]}
  END{for (i in a){print i,0,a[i],a[i]}}' ref_file head_file

The explanation:

  • -F";" specifies the semicolon ; as delimiter.
  • The BEGIN{...} rule is executed once only, before the first input record is read. In that rule, the OFS (output field separator) is set to comma , and the header line is printed: FUNCTION,HEAD,REF,DIFF.
  • FNR==NR applies for the first file being processed: the ref_file.
    • a[$2]=$1;next The files contents are now stored in an array called a with the index $2 and the value $1.
  • {...} that block applies for every line of the second file, the head_file:
    • print ... the values are printed with the corresponding value in the previously created array. Notice [$2]*1; when the value is empty the multiplication with *1 ends in a zero 0.
    • delete a[$2]: When finished delete the array element.
  • The END{...} rule is executed once only, after the last input record is read.
    • for (i in a): Loop trough the rest of the array a which is not yet deleted.
    • print ...: Print its indexes and values.

The output:

FUNCTION,HEAD,REF,DIFF
int builder(,2345,2000,-345
char type::edit::display <test>(,1000,500,-500
void unamed_string_tree*,250,0,-250
fillTest*(,0,3000,3000
  • It worked properly but using nawk and not awk. Is there a way not to display functions having REF=HEAD=0 ? @chaos – ekassis Sep 26 '15 at 22:42
  • I found the solution. nawk -F";" 'BEGIN{OFS=","; print "FUNCTION,HEAD,REF,DIFF"} FNR==NR{a[$2]=$1;next} {if ($1 != 0) {print $2,$1,a[$2]*1,a[$2]-$1} ; delete a[$2]} END{for (i in a){if (a[i] != 0) print i,0,a[i],a[i]}}' ref_file head_file – ekassis Sep 27 '15 at 10:29

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.