#1 Le 01/03/2016, à 16:03
- Chris88
Expression avec Grep - First occurence
Bonjour à tous. Je suis sur un script où je bloque et j'ai besoin de vous pour m'aider.
Ma commande :
echo TotoPTitiPTataP | grep -o .*P
Ca donne :
TotoPTitiPTataP
J'aimerais extraire ce qui se trouve avant la première occurrence de P et pas avant la dernière :
TotoP
Chris
Hors ligne
#2 Le 01/03/2016, à 16:15
- credenhill
Re : Expression avec Grep - First occurence
hello
$ echo TotoPTitiPTataP | grep -o '^[^P]*P'
TotoP
Hors ligne
#3 Le 01/03/2016, à 17:54
- Chris88
Re : Expression avec Grep - First occurence
Merci
Hors ligne
#4 Le 01/03/2016, à 18:46
- Chris88
Re : Expression avec Grep - First occurence
J'utilise la echo TotoPTitiPTataP | grep -o '[^P]*P' (sans le premier ^), ça me permet d'obtenir tous les matchs
TotoP
TitiP
TataP
Maintenant, je voudrais obtenir un match par variable, pour ça, j'essai :
targets=$(echo TotoPTitiPTataP | grep -o '[^P]*P')
echo $targets[0] => print all entry
echo $targets[1] => Nothing
Comment puis je mettre chaque match dans chaque entrée d'un tableau ?
Merci pour tout
Hors ligne
#5 Le 01/03/2016, à 18:54
- pingouinux
Re : Expression avec Grep - First occurence
Bonsoir,
S'il n'y a pas d'espaces dans la chaîne de caractères :
$ targets=( $(grep -o '[^P]*P' <<<"TotoPTitiPTataP") )
$ echo ${targets[0]}
TotoP
$ echo ${targets[1]}
TitiP
$ echo ${targets[2]}
TataP
Ajouté : S'il y a des espaces
$ n=0;while read var; do targets[$((n++))]="$var"; done < <(grep -o '[^P]*P' <<<"To toPTi tiPTa taP")
$ echo "${targets[0]}"
To toP
$ echo "${targets[1]}"
Ti tiP
$ echo "${targets[2]}"
Ta taP
On peut même simplifier un peu
$ n=0;while read var; do targets[n++]=$var; done < <(grep -o '[^P]*P' <<<"To toPTi tiPTa taP")
Dernière modification par pingouinux (Le 01/03/2016, à 19:16)
Hors ligne
#6 Le 02/03/2016, à 08:54
- credenhill
Re : Expression avec Grep - First occurence
et aussi
$ readarray t < <(grep -o '[^P]*P' <<<"To toPTi tiPTa taP")
$ printf "%s" "${t[@]}"
To toP
Ti tiP
Ta taP
Hors ligne