linuxbashshellawk

Awk using index with Substring


I have one command to cut string.

I wonder detail of control index of command in Linux "awk"

I have two different case.

I want to get word "Test" in below example string.

1. "Test-01-02-03"    
2. "01-02-03-Test-Ref1-Ref2

First one I can get like

substr('Test-01-02-03',0,index('Test-01-02-03',"-"))
-> Then it will bring result only "test"

How about Second case I am not sure how can I get Test in that case using index function.

Do you have any idea about this using awk?

Thanks!


Solution

  • This is how to use index() to find/print a substring:

    $ cat file
    Test-01-02-03
    01-02-03-Test-Ref1-Ref2
    
    $ awk -v tgt="Test" 's=index($0,tgt){print substr($0,s,length(tgt))}' file
    Test
    Test
    

    but that may not be the best solution for whatever your actual problem is.

    For comparison here's how to do the equivalent with match() for an RE:

    $ awk -v tgt="Test" 'match($0,tgt){print substr($0,RSTART,RLENGTH)}' file
    Test
    Test
    

    and if you like the match() synopsis, here's how to write your own function to do it for strings:

    awk -v tgt="Test" '
    function strmatch(source,target) {
        SSTART  = index(source,target)
        SLENGTH = length(target)
        return SSTART
    }
    
    strmatch($0,tgt){print substr($0,SSTART,SLENGTH)}
    ' file