0

I have the following values in this format in a file:

Filevalue.txt

abc
123
dev
456
hij
567
123
542

I need to add the numerical values from the character values which are below it

Output

abc 123
dev 456
hij 1232

Anyhelp will be deeply appreciated?

1
  • Please show the what you have written so far, so that we can see where you are stuck. Commented Mar 21, 2017 at 10:17

2 Answers 2

2

Here's another awk that mantains the order.

Example

$ awk '/[0-9]+/{a+=$1;next}a{print a;a=0}{printf($1FS);a=0}END{print a}' file
abc 123
dev 456
hij 1232

Explanation

/[0-9]+/{a+=$1;next}:When a number is detected as the content of the record, it's value is accumulated into a var, then next is used to stop further processing and pass the flow to the next record.

a{print a;a=0}: ONLY when the counter is not null we print a value that correspond to the previous word and initialize it.

{printf($1FS);a=0}: Print current record and the separator avoiding the carriage return. This is applied to all text records.

END{print a}: Show the final counter that will remain after the last record.

Sign up to request clarification or add additional context in comments.

1 Comment

Even without arrays! Nice!
1

It's possible to do this by using awk and arrays:

$ awk '{if($1!~/^[0-9]+$/){cur=$1}else{sums[cur]+=$1}}END{for(el in sums){printf("%s %d\n",el,sums[el])}}' Filevalue.txt 
hij 1232
dev 456
abc 123

Here is the same code but written to the file sum.awk and with comments:

# this block will be executed for every line in the file
{
    # if current processing line is not a number, then it's a name of the next
    # group, let's save it to cur variable
    if ($1 !~ /^[0-9]+$/) {
        cur = $1
    } else {
        # here we're summing values
        sums[cur] += $1
    }
}
# this block will be executed at the end of file processing, here we're
# printing array with sums
END {
    for (el in sums) {
        printf("%s %d\n", el, sums[el])
    }
}

Use it like this:

$ awk -f sum.awk Filevalue.txt 
hij 1232
dev 456
abc 123

The only downside of using awk here is that it doesn't preserve keys order.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.