logo

Bash Разделен низ

В тази тема сме дефинирали как да разделим низ в скриптове на bash shell.

В някои случаи може да се наложи да разделим низовите данни, за да изпълним някои специфични задачи. Повечето от езиците за програмиране съдържат вградена функция 'split' за разделяне на всички низови данни на множество части. Bash обаче не съдържа такъв тип вградена функция. Но можем да използваме разделители, за да разделяме всички низови данни в bash скриптове. Разделителят може да бъде или един знак, или низ с множество символи.

Вижте методите по-долу, за да разберете как да разделите низ в bash shell:

Разделете с помощта на променлива $IFS

Следват стъпките за разделяне на низ в bash с помощта на $IFS:

  • $IFS е специална вътрешна променлива, която се използва за разделяне на низ на думи. Променливата $IFS се нарича ' Вътрешен разделител на полето ', което определя как Bash разпознава границите. $IFS се използва за присвояване на конкретния разделител [ IFS='' ] за разделяне на низа. Бялото пространство е стойност по подразбиране на $IFS. Можем обаче да използваме и стойности като ' ', ' ', '-' и т.н. като разделител.
  • След задаване на разделителя низът може да се чете с две опции: '-r' и '-a'. т.е. четене -ra ARR <<< '$str' .
    Тук опцията '-r' се използва, за да се определи, че обратната наклонена черта () е символ, а не екраниращ знак. Опцията '-a' се използва, за да се определи, че думите (разделени с $IFS) се присвояват на последователния индекс на масива, започващ от нула.
  • След това прилагаме bash 'for' цикъл за достъп до токените, които са разделени в масив.

Нека разберем този механизъм с помощта на няколко примера:

Пример 1: Bash разделяне на низ чрез интервал

В този пример низ е разделен с помощта на разделител за интервал.

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'>

В този bash скрипт сме използвали следните разширения на параметри:

    ${parameter%%word}
    Той премахва най-дългия съвпадащ суфиксен шаблон.${parameter#word}
    Той премахва най-краткия съвпадащ модел на префикс.

Изход

Bash Разделен низ

Пример 3: Bash Split String с помощта на Trim Command

В този пример използвахме командата trim (tr), за да разделим низ. Вместо да се използва командата read, командата trim се използва за разделяне на низ върху разделителя.

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 

Изход

Bash Разделен низ

Забележка: Трябва да се отбележи, че елементите на масива се разделят на „разделител за интервал“, ако приложим команда за изрязване, за да разделим низ. Например елементи като „Windows OS“ ще се третират като две различни думи.

Заключение

В тази тема демонстрирахме как да разделим низ в bash скриптове с различни типове сценарии със или без използване на разделител.