如何将perl索引脚本转换为bash函数

问题描述 投票:0回答:2

我想使用

perl
从 bash 函数中的
index of
any given string
获取
substring

以下是从perl脚本获取indexOf值的示例:

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: $index\n";

Output:

Position of 'the' in the string: 10

这是测试.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: $index\n";
    
    "
    
    printf "%s" "$index"
}

result="$(bash_function_get_index_from_perl_script)"

echo "result is: $result"

这是预期的输出:

result is: 10

如何落实“

bash_function_get_index_from_perl_script
”?

bash perl ubuntu indexof
2个回答
0
投票

方法有很多。例如,您可以将脚本发送到 perl 的标准输入:

#!/bin/bash

bash_function_get_index_from_perl_script() {
    index=$(perl <<- '_PERL_'
    $string = 'Geeks are the best';
    $index = index $string, 'the';
    print "Position of 'the' in the string: $index\n";
    _PERL_
    )
    printf "%s" "$index"
}

result=$(bash_function_get_index_from_perl_script)

echo "result is: $result"

但是你不需要 Perl,你可以使用 bash 本身的参数扩展来找到位置:

#!/bin/bash

bash_function_get_index() {
    string='Geeks are the best';
    before=${string%the*}
    index=${#before}
    printf %s "$index"
}

result=$(bash_function_get_index)

echo "Position of 'the' in the string: $result"

0
投票

bashstring的索引

试试这个:

string="Geeks are the best" sub=the lhs=${string%$sub*} echo ${#lhs} 10
作为函数(使用 

-v

 选项来分配变量而不是回显。为了避免无用的分叉):

indexOf() { if [[ $1 == -v ]]; then local -n result="$2" shift 2 else local result fi local string="$2" substr="$1" lhs lhs=${string%$substr*} printf -v result %d ${#lhs} case ${result@A} in result=* ) echo $result;;esac }
然后

indexOf the "Geeks are the best" 10 indexOf -v var the "Geeks are the best" echo $var 10
    
© www.soinside.com 2019 - 2024. All rights reserved.