Search code examples
awktext-processing

start from first space before the value


I don't know how i can say "start from first space before the value" or "Closest space before the word". my code like (linux bash awk):

data= "your website is the best website"
value = "t w"

when i used this code to print the line from value to end of line:

if ( index($0, value))
    print substr($0, index($0,value)) 

the result was:

t website

please i want to print it like:

best website

to print from the word which containt first letter?


Solution

  • With GNU awk, build a regex that adds "non-blanks" before and after the value

    gawk 'BEGIN {
        data = "your website is the best website"
        value = "t w"
        regex = "[^[:blank:]]+" value "[^[:blank:]]+"
        if (match(data, regex, m)) {print m[0]}
    }'
    
    best website
    

    With any awk, use the RSTART and RLENGTH variables set by the match(str, re) function:

    awk 'BEGIN {
        data = "your website is the best website"
        value = "t w"
        regex = "[^[:blank:]]+" value "[^[:blank:]]+"
        if (match(data, regex)) {print substr(data, RSTART, RLENGTH)}
    }'
    

    Or, don't treat value as a regex: use index() and look backwards and forwards for spaces that delimit the words:

    awk 'BEGIN {
        data = "your website is the best website"
        value = "t w"
        start = index(data, value)
        if (start > 0) {
            i = start; while (i > 0 && substr(data, i, 1) != " ") {i--}
            j = start + length(data); while (j < length(data) && substr(data, j, 1) != " ") {j++}
            print substr(data, i+1, j-i+1)
        }
    }'```