2

I have strings that are supposed to match with numbers.

For example,

one is equal to 1

Now, I have a file that separates columns with ; and I want to write an awk expression that checks if the SUM of the first column $1 is equal to $2.

Here is an example of how the file is structured

oNe-oNE ; 2
one-too ; 1

SOLUTION [needs improvement] I have it working with only two arguments for the string, like one-one, but I need to adapt it to accept more, like One-TOO-pots-one-one (unlimited really).

awk 'BEGIN{n=split("one 1 too 2 hello",b," ");for (i=1;i<n;i+=2) a[b[i]]=b[i+1]} {split($1,c,"-");f=tolower(c[1]);s=tolower(c[2]);print $0,"; "(a[f]+a[s]==$3?"match":"not")}' file
  • Please post your solution as an answer below – Sylvain Pineau Mar 5 '15 at 19:07
1

Given

oNe-oNE ; 2
one-too ; 1
One-TOO-pots-one-one ; 21
one-foo ; 1

then

awk -F\; '
BEGIN {
  val["one"]=1;val["too"]=2;val["hello"]=4;val["pots"]=16;
}

{
  split($1,a,"[- ]");
  t = 0;
  for (i in a) {
    t += val[tolower(a[i])];
  }
  if (t == $2) print $0, "match"; else print $0, "not";
}' file

produces

oNe-oNE ; 2 match
one-too ; 1 not
One-TOO-pots-one-one ; 21 match
one-foo ; 1 match
  • @Plaurs sorry, I don't understand what you're asking – steeldriver Mar 6 '15 at 2:45
0

Here is how I would do this:

  1. Put string-to-number lines into a file of its own and parse it.
  2. Manipulate FS to ease parsing of the CSV file.

One way to achieve this:

sum.awk

FNR==NR { h[$1] = $NF; next }
FNR==1  { FS=" *[-;] *"     }
{ print $0 " ; " (h[tolower($1)] + h[tolower($2)] == $3 ? "match" : "not") }

Run it like this:

awk -f sum.awk string-to-number.txt csv.txt

Output:

oNe-oNE ; 2 ; match
one-too ; 1 ; not

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.