logo

Bash Split String

I dette emne har vi defineret, hvordan man deler en streng i bash shell scripting.

I nogle tilfælde skal vi muligvis opdele strengdataene for at udføre nogle specifikke opgaver. De fleste programmeringssprog indeholder en indbygget funktion 'split' til at opdele strengdata i flere dele. Bash indeholder dog ikke en sådan type indbygget funktion. Men vi kan bruge skilletegn til at opdele strengdata i bash-scripting. Afgrænsningstegnet kan enten være et enkelt tegn eller en streng med flere tegn.

Tjek nedenstående metoder for at forstå, hvordan man splitter streng i en bash-skal:

Opdel ved hjælp af $IFS variabel

Følgende er trinene til at opdele en streng i bash ved hjælp af $IFS:

  • $IFS er en speciel intern variabel, som bruges til at opdele en streng i ord. $IFS variabel kaldes ' Intern feltseparator ' som bestemmer, hvordan Bash genkender grænser. $IFS bruges til at tildele den specifikke skilletegn [ IFS='' ] for at dele strengen. Det hvide mellemrum er en standardværdi på $IFS. Vi kan dog også bruge værdier som ' ', ' ', '-' osv. som skilletegn.
  • Efter tildeling af afgrænsningstegnet kan en streng læses med to muligheder: '-r' og '-a'. dvs. læs -ra ARR <<< '$str' .
    Her bruges muligheden '-r' til at definere, at omvendt skråstreg () er et tegn i stedet for et escape-tegn. Valgmuligheden '-a' bruges til at definere, at ordene (adskilt af $IFS) er tildelt til det sekventielle indeks for array, der begynder ved nul.
  • Derefter anvender vi bash 'for' loop for at få adgang til tokens, som er opdelt i et array.

Lad os forstå denne mekanisme ved hjælp af nogle eksempler:

Eksempel 1: Bash Split streng efter mellemrum

I dette eksempel opdeles en streng ved hjælp af et mellemrumstegn.

Bash Script

 #!/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'>

I dette bash-script har vi brugt følgende parameter-udvidelser:

    ${parameter%%word}
    Det fjerner det længste matchende suffiksmønster.${parameter#word}
    Det fjerner det korteste matchende præfiksmønster.

Produktion

Bash Split String

Eksempel 3: Bash Split String ved hjælp af Trim Command

I dette eksempel har vi brugt trim (tr) kommando til at opdele en streng. I stedet for at bruge read-kommandoen, bruges trim-kommandoen til at opdele en streng på afgrænseren.

Bash Script

 #!/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 

Produktion

Bash Split String

Bemærk: Det skal bemærkes, at array-elementer er opdelt på 'space delimiter', hvis vi anvender en trim-kommando til at opdele en streng. For eksempel vil elementer som 'Windows OS' blive behandlet som to forskellige ord.

Konklusion

I dette emne demonstrerede vi, hvordan man opdeler en streng i bash-scripting med forskellige typer scenarier med eller uden brug af skilletegn.