I want to use perl
to get the index of
from any given string
and substring
in bash function.
Here is the example for getting the indexOf value from perl script:
https://www.geeksforgeeks.org/perl-index-function/
#!/usr/bin/perl
# String from which Substring
# is to be searched
$string = "Geeks are the best";
# Using index() to search for substring
$index = index ($string, 'the');
# Printing the position of the substring
print "Position of 'the' in the string: $indexn";
Output:
Position of 'the' in the string: 10
Here is the test.sh:
#!/bin/bash
bash_function_get_index_from_perl_script() {
local index="-1"
# Here is the dummy code
# as I don't know how to convert
# the perl script to bash command lines
# and get the result from perl script
index="
#!/usr/bin/perl
# String from which Substring
# is to be searched
$string = "Geeks are the best";
# Using index() to search for substring
$index = index ($string, 'the');
# Printing the position of the substring
print "Position of 'the' in the string: $indexn";
"
printf "%s" "$index"
}
result="$(bash_function_get_index_from_perl_script)"
echo "result is: $result"
Here is the expected output:
result is: 10
How to implement the "bash_function_get_index_from_perl_script
"?
Update:
Here is the bash function for testing:
#!/bin/bash
bash_function_get_index() {
local string="$1"
local search_string="$2"
before=${string%${search_string}*}
index=${#before}
printf "%s" "$index"
}
echo "test 1: $(bash_function_get_index "hello world" "wo")"
echo "test 2: $(bash_function_get_index "hello world" "wox")"
Here is the output:
test 1: 6
test 2: 11
The result of "test 2" is wrong, it should be:
test 2: -1
I want to implement the same "indexOf" function from Java:
https://www.w3schools.com/java/ref_string_indexof.asp
index_of() {
local string="$1"
local search_string="$2"
local fromIndex="$3"
local index=""
# Get the real index here, the result shoule be the same as the Java's "indexOf"
printf "%s" "$index"
}
2
Answers
There are many ways. For example, you can send the script to the standard input of perl:
But you don’t need Perl for that, you can find the position using parameter expansion in bash itself:
Index Of substring in string in bash
Try this:
As a function
with
-v
option to assign a variable instead of echoing. In order to avoid useless forks:With an exeption: if substring not found, then answer is
-1
.Tests and syntax
Then
Then for avoiding forks
var=$(function...)
, use-v var
option!!should produce:
Why do I insist about avoiding forks
Just try to run 1’000 time the job:
From approx 1 seconds to approx 3 100th of second!!
No comment!