Linux 如何在shell中找到特定的字符位置
对于给定字符串:Linux 如何在shell中找到特定的字符位置,linux,bash,shell,Linux,Bash,Shell,对于给定字符串: a="This is test.txt file" 如何在shell环境中找到的位置?它应该使用BASH返回13: 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 或使用awk: awk -F. '{pri
a="This is test.txt file"
如何在shell环境中找到
的位置?它应该使用BASH返回13
:
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
或使用awk
:
awk -F. '{print length($1)+1}' <<< "$a"
13
awk-F.{打印长度($1)+1}'使用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;
}
#包括
#包括
int main(){
char a[]=“这是test.txt文件”;
int i=0;
而(i
显然,这是一个重复的问题,但并非所有答案都在两页上
更多有用的信息可在
此脚本将查找单个字符或多个字符的字符串。
我修改了另一页上的代码,以适应这里的问题:
#strindex.sh
A="This is test.txt file"
B=.
strindex() {
X="${1%%$2*}"
[[ "$X" = "$1" ]] && echo -1 || echo "$[ ${#X} + 1 ]"
}
strindex "$A" "$B"
#end
这将按要求返回13
在上面的示例中,我更愿意使用A=“$(cat$1)”和B=“$2”定义变量“A”和“B”,这样脚本就可以用于命令行中的任何文件和任何搜索字符串。
注意,我还将另一页示例中的变量更改为大写。这不是强制性的,但有些人认为大写的变量是一种很好的约定,更易于阅读和识别。非常好。你能简单解释一下2行吗?“${a%%.*}”?当然,我在回答中添加了一些解释