start from first space before the value

Viewed 59

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?

3 Answers

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)
    }
}'```

With your shown samples, please try following awk code, written and tested in GNU awk.

awk -v RS='\\s*\\S+t w\\S+' 'RT{sub(/^\s+/,"",RT);print RT}' Input_file

OR in case you want to pass a variable as an Input to awk command try following then:

awk -v RS='\\s*\\S+t w\\S+' 'RT{sub(/^\s+/,"",RT);print RT}' <<< "$data"
echo "your website is the best website" | 

mawk 'sub(".+ ","&"_,$(NF-!__))+sub("^[^"_"]*"_,__)' \_='\3' FS='t w' OFS='t w'
best website
Related