Home > Back-end >  How to use awk method to implement the startsWith function on bash script
How to use awk method to implement the startsWith function on bash script

Time:04-17

I'm trying to use awk to implement the startsWith function in bash script, but it is not work.

https://www.gnu.org/software/gawk/manual/html_node/String-Functions.html

#! /bin/bash


starts_with()
{
    local string=$1
    local substring=$2
    
    local index=$(printf "%s" "$string" | awk 'BEGIN { print index("$string", "$substring") }')
    
    if [[ "$index" == "1" ]]
    then
        echo "true" : $string : $substring
    else
        echo "false" : $string : $substring
    fi
}

starts_with key1="value" key1=
starts_with key2="value" wrong_key=

Here is the output:

false : key1=value : key1=
false : key2=value : wrong_key=

But the awk page says:

index(in, find)

    Search the string in for the first occurrence of the string find, and return the position in characters where that occurrence begins in the string in. Consider the following example:

    $ awk 'BEGIN { print index("peanut", "an") }'
    -| 3

    If find is not found, index() returns zero.

    With BWK awk and gawk, it is a fatal error to use a regexp constant for find. Other implementations allow it, simply treating the regexp constant as an expression meaning ‘$0 ~ /regexp/’. (d.c.)

What's wrong in the above starts_with function and how to fix?

CodePudding user response:

There's no point in using awk when you can do it directly in bash?

#!/bin/bash
starts_with() {
    local string="$1"
    local substring="$2"

    if [[ $string == "$substring"* ]]
    then
        echo "true : $string : $substring"
    else
        echo "false : $string : $substring"
    fi
}
  • Related