bash 如何在shell中找到某个字符位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43946711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:08:40  来源:igfitidea点击:

How to find certain character position in shell

linuxbashshell

提问by Mitko Gurbanski

For a given string:

对于给定的字符串:

a="This is test.txt file"

How to find position of the .in a shell environment? It should return 13.

如何.在shell环境中找到的位置?它应该返回13

回答by anubhava

Using BASH:

使用 BASH:

a="This is test.txt file"
s="${a%%.*}"            # remove all text after DOT and store in variable s
echo "$(( ${#s} + 1 ))" # get string length of $s + 1

13

Or using awk:

或使用awk

awk -F. '{print length()+1}' <<< "$a"
13

回答by vishalknishad

Using C:

使用 C:

#include <stdio.h>
#include <string.h>

int main() {

    char a[] = "This is test.txt file";

    int i = 0;
    while( i < strlen(a) ) {
            if( a[i] == '.' ) {
                    printf("%d", i + 1);
                    break;
            }
            i++;
    }

    return 0;
}

回答by unifex

Clearly this is a duplicated question but all answers are not on both pages.

显然,这是一个重复的问题,但并非所有答案都在两页上。

Additional useful information can be found at Position of a string within a string using Linux shell script?

其他有用的信息可以在使用 Linux shell 脚本的字符串中的字符串位置找到

This script will find a single character or a multi-character string. I've modified the code on the other page to fit the question here:

此脚本将查找单个字符或多字符字符串。我已经修改了另一页上的代码以适应这里的问题:

#strindex.sh
A="This is test.txt file"
B=.
strindex() {
X="${1%%*}"
[[ "$X" = "" ]] && echo -1 || echo "$[ ${#X} + 1 ]"
}
strindex "$A" "$B"
#end

This returns 13 as requested.

这将根据请求返回 13。

In the above example I would prefer to define the variables 'A' and 'B' with A="$(cat $1)" and B="$2" so the script can be used on any file and any search string from the command line. Note I also changed the variables to upper case from the other page's example. This is not mandatory but some people think variables in upper case is a nice convention and easier to read and identify.

在上面的例子中,我更愿意用 A="$(cat $1)" 和 B="$2" 定义变量 'A' 和 'B',这样脚本就可以用于任何文件和命令中的任何搜索字符串线。请注意,我还将其他页面示例中的变量更改为大写。这不是强制性的,但有些人认为大写的变量是一个很好的约定,更容易阅读和识别。