PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, May 14, 2022

[FIXED] How to use awk method to implement the startsWith function on bash script

 May 14, 2022     awk, bash, ubuntu, unix     No comments   

Issue

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?


Solution

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
}


Answered By - Fravadona
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing