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
1
  • Please post your solution as an answer below Mar 5, 2015 at 19:07

2 Answers 2

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
1
  • @Plaurs sorry, I don't understand what you're asking Mar 6, 2015 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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .