Linux команда разбить строку

Bash split string into array using 4 simple methods

How to create array from string with spaces? Or In bash split string into array? We can have a variable with strings separated by some delimiter, so how to split string into array by delimiter?

The main reason we split string into array is to iterate through the elements present in the array which is not possible in a variable.

Sample script with variable containing strings

For example in this script I have a variable myvar with some strings as element

# cat /tmp/split-string.sh #!/bin/bash myvar="string1 string2 string3" echo "My array: $myvar" echo "Number of elements in the array: $ "

Here if I want to iterate over individual element of the myvar variable, it is not possible because this will considered as a variable and not an array.
This we can verify by counting the number of elements in the myvar variable

When we execute the script, we see that number of elements in myvar is 1 even when we have three elements

# /tmp/split-string.sh My array: string1 string2 string3 Number of elements in the array: 1

To overcome this we convert and split string into array. Now your variable can have strings or integers or some special characters, so depending upon your requirement you can choose different methods to convert string into an array. I will cover some of them with examples:

Method 1: Bash split string into array using parenthesis

Normally to define an array we use parenthesis () , so in bash to split string into array we will re-define our variable using open and closed parenthesis

# cat /tmp/split-string.sh #!/bin/bash myvar="string1 string2 string3" # Redefine myvar to myarray using parenthesis myarray=($myvar) echo "My array: $ " echo "Number of elements in the array: $ "

Bash split string into array using 4 simple methods

Next execute the shell script. We see know we have 3 elements in the array

# /tmp/split-string.sh My array: string1 string2 string3 Number of elements in the array: 3

Method 2: Bash split string into array using read

We can use read -a where each input string is an indexed as an array variable.
the default delimiter is considered as white space so we don’t need any extra argument in this example:

# cat /tmp/split-string.sh #!/bin/bash myvar="string1 string2 string3" # Storing as array into myarray read -a myarray $myvar echo "My array: $ " echo "Number of elements in the array: $ "

Bash split string into array using 4 simple methods

Execute the script. Now the myarray contains 3 elements so bash split string into array was successful

# /tmp/split-string.sh My array: string1 string2 string3 Number of elements in the array: 3

Method 3: Bash split string into array using delimiter

We can combine read with IFS (Internal Field Separator) to define a delimiter.
Assuming your variable contains strings separated by comma character instead of white space as we used in above examples
We can provide the delimiter value using IFS and create array from string with spaces

# cat /tmp/split-string.sh #!/bin/bash myvar="string1,string2,string3" # Here comma is our delimiter value IFS="," read -a myarray $ " echo "Number of elements in the array: $ "

Bash split string into array using 4 simple methods

Execute the shell script, and the variable is successfully converted into array and the strings can be iterated separately

# /tmp/split-string.sh My array: string1 string2 string3 Number of elements in the array: 3

Method 4: Bash split string into array using tr

tr is a multi purpose tool. We will use this tool to convert comma character into white space and further using it under parenthesis from Method 1 to create array from string with spaces
So you can use this with any other delimiter, although it may not work under all use cases so you should verify this based on your requirement

# cat /tmp/split-string.sh #!/bin/bash myvar="string1,string2,string3" # Change comma (,) to whitespace and add under braces myarray=(`echo $myvar | tr ',' ' '`) echo "My array: $ " echo "Number of elements in the array: $ "

Bash split string into array using 4 simple methods

# /tmp/split-string.sh My array: string1 string2 string3 Number of elements in the array: 3

Some more examples to convert variable into array in bash

Based on your requirement you can choose the preferred method.

For example here I have a variable with newline as delimiter. So here I can use the first method. This will create array from string with spaces

# cat /tmp/split-string.sh #!/bin/bash myvar="string1 string2 string3" myarray=($myvar) echo "My array: $ " echo "Number of elements in the array: $ "

Execute the script. You can verify using the number of elements in the array

[root@rhel-8 ~]# /tmp/split-string.sh My array: string1 string2 string3 Number of elements in the array: 3

We can now iterate through the elements which are part of the array in a loop

# cat /tmp/split-string.sh #!/bin/bash myvar="string1 string2 string3" myarray=($myvar) echo "My array: $ " echo "Number of elements in the array: $ " for (( i=0; i; i++ )); do echo "$$i]>" done

Execute the script to verify

# /tmp/split-string.sh My array: string1 string2 string3 Number of elements in the array: 3 string1 string2 string3

Lastly I hope the steps from the article for bash split string into array on Linux was helpful. So, let me know your suggestions and feedback using the comment section.

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

5 thoughts on “Bash split string into array using 4 simple methods”

Tks. Great. Can we use the array element “$” for regex search in grep/sed/awk. If so, some examples pl. Reply

Источник

Как разделить строку в скрипте Bash

Favorite

Добавить в избранное

Допустим, у вас есть длинная строка с несколькими словами, разделенными запятой или подчеркиванием. Вы хотите разбить эту строку и извлечь отдельные слова.

Вы можете разделить строки в bash, используя разделитель внутренних полей (IFS) и команду чтения, или вы можете использовать команду обрезки. Позвольте нам показать вам, как это сделать на примерах.

Метод 1: Разделить строку с помощью команды чтения в Bash

Вот наш пример сценария для разделения строки с помощью команды read:

#!/bin/bash # # Скрипт для разделения строки на основе разделителя my_string="Ubuntu;Linux Mint;Debian;Arch;Fedora" IFS=';' read -ra my_array " do echo $i done

Часть, которая разбивает строку, находится здесь:

IFS определяет разделитель, по которому вы хотите разбить строку. В нашем случае это точка с запятой. Это может быть что угодно: пробел, табуляция, запятая или даже алфавит.

IFS в команде read разделяет входные данные в разделителе. Команда read читает необработанный ввод (опция -r), поэтому интерпретирует обратную косую черту буквально, а не обрабатывает их как escape-символ. Опция -a с командой read сохраняет слово read в массиве.

Проще говоря, длинная строка разбивается на несколько слов, разделенных разделителем, и эти слова хранятся в массиве.

Теперь вы можете получить доступ к массиву, чтобы получить любое слово, которое вы хотите, или использовать цикл for в bash, чтобы напечатать все слова одно за другим, как мы делали в приведенном выше сценарии.

Вот вывод вышеприведенного скрипта:

Ubuntu
Linux Mint
Debian
Arch
Fedora

Способ 2: разделить строку с помощью команды trim в Bash

Это пример разделения строки bash с использованием команды trim (tr):

#! / bin / bash # # Скрипт для разделения строки на основе разделителя
my_string="Ubuntu;Linux Mint;Debian;Arch;Fedora" my_array=($(echo $my_string | tr ";" "\n")) #Print the split string for i in "$" do echo $i done

Этот пример почти такой же, как и предыдущий. Вместо команды чтения, команда trim используется для разделения строки на разделителе.

Проблема с этим подходом состоит в том, что элемент массива разделен на «пробел». Из-за этого такие элементы, как «Linux Mint», будут рассматриваться как два слова.

Вот вывод вышеприведенного скрипта:

Ubuntu
Linux
Mint
Debian
Arch
Fedora

Вот почему мы предпочитаем первым способом разбивать строку в bash.

Мы надеемся, что эта краткая статья по bash помогла вам разбить строку.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Источник

Читайте также:  Virtualbox linux share files
Оцените статью
Adblock
detector