logo

Chaîne divisée Bash

Dans cette rubrique, nous avons défini comment diviser une chaîne dans les scripts shell bash.

Dans certains cas, nous devrons peut-être diviser les données de chaîne pour effectuer certaines tâches spécifiques. La plupart des langages de programmation contiennent la fonction intégrée « split » pour diviser toute donnée de chaîne en plusieurs parties. Cependant, bash ne contient pas ce type de fonction intégrée. Mais nous pouvons utiliser des délimiteurs pour diviser n'importe quelle chaîne de données dans les scripts bash. Le délimiteur peut être soit un seul caractère, soit une chaîne comportant plusieurs caractères.

Consultez les méthodes ci-dessous pour comprendre comment diviser une chaîne dans un shell bash :

Fractionner à l'aide de la variable $IFS

Voici les étapes pour diviser une chaîne dans bash à l'aide de $IFS :

  • $IFS est une variable interne spéciale utilisée pour diviser une chaîne en mots. La variable $IFS est appelée ' Séparateur de champ interne ' qui détermine la façon dont Bash reconnaît les limites. $IFS est utilisé pour attribuer le délimiteur spécifique [ IFS='' ] pour diviser la chaîne. L'espace blanc est une valeur par défaut de $IFS. Cependant, nous pouvons également utiliser des valeurs telles que ' ', ' ', '-' etc. comme délimiteur.
  • Après avoir attribué le délimiteur, une chaîne peut être lue par deux options : '-r' et '-a'. c'est à dire., lire -ra ARR <<< '$str' .
    Ici, l'option '-r' est utilisée pour définir que la barre oblique inverse () est un caractère plutôt qu'un caractère d'échappement. L'option '-a' est utilisée pour définir que les mots (séparés par $IFS) sont affectés à l'index séquentiel du tableau commençant à zéro.
  • Ensuite, nous appliquons la boucle bash 'for' pour accéder aux jetons qui sont divisés en un tableau.

Comprenons ce mécanisme à l'aide de quelques exemples :

Exemple 1 : Bash diviser la chaîne par espace

Dans cet exemple, une chaîne est divisée à l'aide d'un délimiteur de caractère espace.

Script bash

 #!/bin/bash #Example for bash split string by space read -p &apos;Enter any string separated by space: &apos; str #reading string value IFS=&apos;&apos; #setting space as delimiter read -ra ADDR &lt;&lt;<'$str' #reading str as an array tokens separated by ifs for i in '${addr[@]}'; #accessing each element of do echo '$i' done < pre> <p> <strong>Output</strong> </p> <p>If we input a string &apos;We welcome you on Javatpoint&apos;, the output will look like this:</p> <img src="//techcodeview.com/img/bash-tutorial/11/bash-split-string.webp" alt="Bash Split String"> <h3>Example 2: Bash Split String by Symbol</h3> <p>In some cases, we may have a requirement to split a string by other delimiters such as a symbol or specific character. In this example, a string is split using a comma (,) symbol character as a delimiter.</p> <p> <strong>Bash Script</strong> </p> <pre> #!/bin/bash #Example for bash split string by Symbol (comma) read -p &apos;Enter Name, State and Age separated by a comma: &apos; entry #reading string value IFS=&apos;,&apos; #setting comma as delimiter read -a strarr &lt;&lt;<'$entry' #reading str as an array tokens separated by ifs echo 'name : ${strarr[0]} ' 'state ${strarr[1]} 'age ${strarr[2]}' < pre> <p> <strong>Output</strong> </p> <img src="//techcodeview.com/img/bash-tutorial/11/bash-split-string-2.webp" alt="Bash Split String"> <h2>Split without $IFS variable</h2> <p>In bash, a string can also be divided without using $IFS variable. The &apos;readarray&apos; command with -d option is used to split the string data. The -d option is applied to define the separator character in the command like $IFS. Moreover, the bash loop is used to print the string in split form.</p> <p>Let&apos;s understand this logic with the help of some example:</p> <h3>Example 1: Bash Split String by Symbol</h3> <p>This example defines how a string value can be split without using $IFS. As per the script, a text value should be entered with the colon (:) sign so that it can be split. Check out the bash script below:</p> <p> <strong>Bash Script</strong> </p> <pre> #!/bin/bash #Example for bash split string without $IFS read -p &apos;Enter any string separated by colon(:) &apos; str #reading string value readarray -d : -t strarr &lt;&lt;<'$str' #split a string based on the delimiter ':' printf '
' #print each value of array with help loop for (( n="0;" < ${#strarr[*]}; n++ )) do echo '${strarr[n]}' done pre> <p> <strong>Output</strong> </p> <img src="//techcodeview.com/img/bash-tutorial/11/bash-split-string-3.webp" alt="Bash Split String"> <h3>Example 2: Bash Split String by another string</h3> <p>In this example, we have used idiomatic expressions where parameter expansion has completed.</p> <p> <strong>Bash Script</strong> </p> <pre> #!/bin/bash #Example for bash split string by another string str=&apos;WeLearnWelcomeLearnYouLearnOnLearnJavatpoint&apos; delimiter=Learn s=$str$delimiter array=(); while [[ $s ]]; do array+=( &apos;${s%%&apos;$delimiter&apos;*}&apos; ); s=${s#*&apos;$delimiter&apos;}; done; declare -p array </pre> <p>In this bash script, we have used the following Parameter- Expansions:</p> <ul> <tr><td>${parameter%%word}</td> <br> It removes the longest matching suffix pattern. </tr><tr><td>${parameter#word}</td> <br> It removes the shortest matching prefix pattern. </tr></ul> <p> <strong>Output</strong> </p> <img src="//techcodeview.com/img/bash-tutorial/11/bash-split-string-4.webp" alt="Bash Split String"> <h3>Example 3: Bash Split String using Trim Command</h3> <p>In this example, we have used trim (tr) command to split a string. Instead of using the read command, the trim command is used to split a string on the delimiter.</p> <p> <strong>Bash Script</strong> </p> <pre> #!/bin/bash #Example to split a string using trim (tr) command my_str=&apos;We;welcome;you;on;javatpoint.&apos; my_arr=($(echo $my_str | tr &apos;;&apos;&apos;
&apos;)) for i in &apos;${my_arr[@]}&apos; do echo $i done </pre> <p> <strong>Output</strong> </p> <img src="//techcodeview.com/img/bash-tutorial/11/bash-split-string-5.webp" alt="Bash Split String"> <h4>Note: It should be noted that array elements are divided on &apos;space delimiter&apos; if we apply a trim command to split a string. For example, elements like &apos;Windows OS&apos; will be treated as two different words.</h4> <h2>Conclusion</h2> <p>In this topic, we demonstrated how to split a string in bash scripting with different types of scenarios with or without using delimiter.</p> <hr></'$str'></pre></'$entry'></pre></'$str'>

Dans ce script bash, nous avons utilisé les extensions de paramètres suivantes :

    ${paramètre%%mot}
    Il supprime le modèle de suffixe correspondant le plus long.${paramètre#mot}
    Il supprime le modèle de préfixe correspondant le plus court.

Sortir

Chaîne divisée Bash

Exemple 3 : Bash Split String à l'aide de la commande Trim

Dans cet exemple, nous avons utilisé la commande trim (tr) pour diviser une chaîne. Au lieu d'utiliser la commande read, la commande trim est utilisée pour diviser une chaîne sur le délimiteur.

Script bash

 #!/bin/bash #Example to split a string using trim (tr) command my_str=&apos;We;welcome;you;on;javatpoint.&apos; my_arr=($(echo $my_str | tr &apos;;&apos;&apos;
&apos;)) for i in &apos;${my_arr[@]}&apos; do echo $i done 

Sortir

Chaîne divisée Bash

Remarque : Il convient de noter que les éléments du tableau sont divisés par un « délimiteur d'espace » si nous appliquons une commande trim pour diviser une chaîne. Par exemple, des éléments tels que « Windows OS » seront traités comme deux mots différents.

Conclusion

Dans cette rubrique, nous avons montré comment diviser une chaîne dans des scripts bash avec différents types de scénarios avec ou sans utilisation de délimiteur.