43 votes

Position d'une chaîne de caractères dans une chaîne de caractères en utilisant le shell Linux script ?

Si j'ai le texte dans une variable shell, par exemple $a :

a="The cat sat on the mat"

Comment puis-je rechercher "cat" et retourner 4 en utilisant un shell Linux script, ou -1 si non trouvé ?

73voto

glenn jackman Points 69748

Avec bash

a="The cat sat on the mat"
b=cat
strindex() { 
  x="${1%%$2*}"
  [[ "$x" = "$1" ]] && echo -1 || echo "${#x}"
}
strindex "$a" "$b"   # prints 4
strindex "$a" foo    # prints -1

31voto

Cercerilla Points 728

Vous pouvez utiliser grep pour obtenir le décalage d'octet de la partie correspondante d'une chaîne :

echo $str | grep -b -o str

Comme dans votre exemple :

[user@host ~]$ echo "The cat sat on the mat" | grep -b -o cat
4:cat

vous pouvez le passer à awk si vous voulez juste la première partie.

echo $str | grep -b -o str | awk 'BEGIN {FS=":"}{print $1}'

9voto

Nikita Rybak Points 36641

J'ai utilisé awk pour cette

a="The cat sat on the mat"
test="cat"
awk -v a="$a" -v b="$test" 'BEGIN{print index(a,b)}'

5voto

qbert220 Points 5029
echo $a | grep -bo cat | sed 's/:.*$//'

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X