J’ai un ssortingng comme
ssortingng = ionworldionfriendsionPeople
Comment puis-je le diviser et le stocker dans un tableau en fonction de l’ ion du motif
array[0]=ionworld array[1]=ionfriends array[2]=ionPeople
J’ai essayé IFS mais je suis incapable de diviser correctement. Quelqu’un peut-il aider à ce sujet.
Edit: j’ai essayé
test=ionworldionfriendsionPeople IFS='ion' read -ra array <<< "$test"
Aussi ma chaîne peut parfois contenir des espaces comme
ssortingng = ionwo rldionfri endsionPeo ple
Vous pouvez utiliser certains opérateurs d’extension de parameters POSIX pour créer la masortingce dans l’ordre inverse.
foo=ionworldionfriendsionPeople tmp="$foo" while [[ -n $tmp ]]; do # tail is set to the result of dropping the shortest suffix # matching ion* tail=${tmp%ion*} # Drop everything from tmp matching the tail, then prepend # the result to the array array=("${tmp#$tail}" "${array[@]}") # Repeat with the tail, until its empty tmp="$tail" done
Le résultat est
$ printf '%s\n' "${array[@]}" ionworld ionfriends ionPeople
Si votre chaîne d’entrée ne contient jamais d’espaces, vous pouvez utiliser l’extension de parameters:
#! /bin/bash ssortingng=ionworldionfriendsionPeople array=(${ssortingng//ion/ }) for m in "${array[@]}" ; do echo ion"$m" done
Si la chaîne contient des espaces, trouvez un autre caractère et utilisez-le:
ifs=$IFS IFS=@ array=(${ssortingng//ion/@}) IFS=$ifs
Vous devrez cependant ignorer le premier élément du tableau qui sera vide.
Utilisation de grep -oP
avec regex lookahead :
s='ionworldionfriendsionPeople' grep -oP 'ion.*?(?=ion|$)' <<< "$s"
Donnera:
ionworld ionfriends ionPeople
Pour remplir un tableau:
arr=() while read -r; do arr+=("$REPLY") done < <(grep -oP 'ion.*?(?=ion|$)' <<< "$s")
Vérifier le contenu du tableau:
declare -p arr declare -a arr='([0]="ionworld" [1]="ionfriends" [2]="ionPeople")'
Si votre grep
ne supporte pas -P
(PCRE) alors vous pouvez utiliser ce gnu-awk:
awk -v RS='ion' 'RT{p=RT} $1!=""{print p $1}' <<< "$s"
Sortie:
ionworld ionfriends ionPeople
# To split ssortingng : # ----------------- ssortingng=ionworldionfriendsionPeople echo "$ssortingng" | sed -e "s/\(.\)ion/\1\nion/g" # To set in Array: # ---------------- ssortingng=ionworldionfriendsionPeople array=(`echo "$ssortingng" | sed -e "s/\(.\)ion/\1 ion/g"`) # To check array content : # ------------------------ echo ${array[*]}