Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all numerical values from a string

Tags:

arrays

string

awk

I have an array (vars) in awk which includes a set of strings made of numbers and alphabets( e.g. px0, px2 ...) I want to split these string into numbers and alphabets and put them into another two dimensional array(comp)

 vars[i]={px0,px2,...}-> comp[i,1]={px,px,...},comp[i,2]={0,2,...}

px0 ->px, 0
px2 ->px, 2 py4 ->py, 4 dxy17 ->dxy,17

I have tried to use sub function and put the results in to a new array,

for (k=l; k<=length(vars); k++){
    j=j+1;vars2[k]=vars[k];
    sub(/[a-z]/,"",vars2[k])
    comp[j,2]=vars2[k]
    printf comp[j,2]
    printf " "
    sub(/[0-9]/,"",vars[k])
    comp[j,1]=vars[k]
    print comp[j,1]
}

but the sub only removes one character from the string.

px0 -> px, x0
like image 221
Raymond gsh Avatar asked Jul 10 '26 00:07

Raymond gsh


1 Answers

I think the major thing needed in the attempt is to specify + in the /[0-9]+/ match. Here is an alternative version which matches and deletes the numbers leaving the string behind.

#! /usr/bin/gawk -f

BEGIN {
    split("", vars)
    vars[1] = "px0"
    vars[2] = "px2"
    vars[3] = "py4"
    vars[4] = "dxy17"

    print "vars[i]={px0,px2,...}-> comp[i,1]={px,px,...},comp[i,2]={0,2,...}"
    print ""

    split("", comp)
    sz = length(vars)
    for (i = 1; i <= sz; ++i) {
        v = vars[i]
        if (match(v, /[0-9]+/))
            sub(comp[i,2] = substr(v, RSTART, RLENGTH), "", v)
        comp[i,1] = v
    }

    for (i = 1; i <= sz; ++i)
        printf("%-6s->%-4s%d\n", vars[i], comp[i,1] ",", comp[i,2])
}

And output:

vars[i]={px0,px2,...}-> comp[i,1]={px,px,...},comp[i,2]={0,2,...}

px0   ->px, 0
px2   ->px, 2
py4   ->py, 4
dxy17 ->dxy,17

Alternative implementations:

We could alternatively find the string part and delete to leave the numeric behind, or we could use two different matches and just drop the results of each in comp[]... but in any case the if (match()) x = substr() pattern (which is POSIX) is our friend.

If we are using gawk, gawk automatically provides the substr() for us if we supply match() an additional parameter a -- the substr() will be dropped into a[0]. Additionally, gawk stuffs a lot of functionality into that extra parameter, and learning about it is worth a dive into the man page.

like image 130
Michael Back Avatar answered Jul 11 '26 17:07

Michael Back



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!