Awk using index with Substring

18,073

Solution 1

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

Solution 2

If these lines are the direct input to awk then the following work:

  • echo 'Test-01-02-03' | awk -F- '{print $1}' # First field
  • echo '01-02-03-Test-Ref1-Ref2' | awk -F- '{print $NF-2}' # Third field from the end.

If these lines are pulled out of a larger line in an awk script and need to be split again then the following snippets will do that:

  • str="Test-01-02-03"; split(str, a, /-/); print a[1]
  • str="01-02-03-Test-Ref1-Ref2"; numfields=split(str, a, /-/); print a[numfields-2]
Share:
18,073
clear.choi
Author by

clear.choi

Updated on June 04, 2022

Comments

  • clear.choi
    clear.choi almost 2 years

    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!