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

How to Split String in Bash Script

In this quick tip, you’ll learn to split a string into an array in Bash script.

Let’s say you have a long string with several words separated by a comma or underscore. You want to split this string and extract the individual words.

You can split strings in bash using the Internal Field Separator (IFS) and read command or you can use the tr command. Let me show you how to do that with examples.

Method 1: Split string using read command in Bash

Here’s my sample script for splitting the string using read command:

#!/bin/bash # # Script to split a string based on the delimiter my_string="Ubuntu;Linux Mint;Debian;Arch;Fedora" IFS=';' read -ra my_array " do echo $i done

The part that split the string is here:

Let me explain it to you. IFS determines the delimiter on which you want to split the string. In my case, it’s a semi colon. It could be anything you want like space, tab, comma or even a letter.

The IFS in the read command splits the input at the delimiter. The read command reads the raw input (option -r) thus interprets the backslashes literally instead of treating them as escape character. The option -a with read command stores the word read into an array in bash.

In simpler words, the long string is split into several words separated by the delimiter and these words are stored in an array.

Now you can access the array to get any word you desire or use the for loop in bash to print all the words one by one as I have done in the above script.

Here’s the output of the above script:

Ubuntu Linux Mint Debian Arch Fedora

Method 2: Split string using tr command in Bash

This is the bash split string example using tr (translate) command:

#!/bin/bash # # Script to split a string based on the delimiter 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

This example is pretty much the same as the previous one. Instead of the read command, the tr command is used to split the string on the delimiter.

The problem with this approach is that the array element are divided on ‘space delimiter’. Because of that, elements like ‘Linux Mint’ will be treated as two words.

Читайте также:  Linux команды для копирования файлов

Here’s the output of the above script:

Ubuntu Linux Mint Debian Arch Fedora

That’s the reason why I prefer the first method to split string in bash.

I hope this quick bash tutorial helped you in splitting the string. In a related post, you may also want to read about string comparison in bash.

And if you are absolutely new to Bash, read our Bash beginner tutorial series.

Источник

Split String in Bash

Split String in Bash

  1. Using the tr Command to Split a String in Bash
  2. Using IFS to Split a String in Bash
  3. Using the read Command to Split a String in Bash
  4. Using Parameter Expansion to Split a String in Bash
  5. Using the cut Command to Split a String in Bash

This tutorial demonstrates splitting a string on a delimiter in bash using the tr command, the IFS , the read command, parameter expansion, and the cut command.

Using the tr Command to Split a String in Bash

The tr command is a short form for translate . It translates, deletes, and squeezes characters from the standard input and writes the results to the standard output.

It is a useful command for manipulating text on the command line or in a bash script. It can remove repeated characters, convert lowercase to uppercase, and replace characters.

In the bash script below, the echo command pipes the string variable, $addrs , to the tr command, which splits the string variable on a delimiter, — . Once the string has been split, the values are assigned to the IP variable.

Then, the for loop loops through the $IP variable and prints out all the values using the echo command.

#!/usr/bin/env bash  addrs="192.168.8.1-192.168.8.2-192.168.8.3-192.168.8.4"  IP=$(echo $addrs | tr "-" "\n")  for ip in $IP do  echo "$ip" done 

The output below shows that the $addr string variable has been split on the delimiter, — , into 4 separate strings.

192.168.8.1 192.168.8.2 192.168.8.3 192.168.8.4 

Using IFS to Split a String in Bash

IFS stands for Internal Field Separator.

The IFS is used for word splitting after expansion and to split lines into words with the built-in read command. The value of IFS tells the shell how to recognize word boundaries.

The default value of the IFS is a space, a tab, and a new line. In the script below, the original value of the IFS has been stored in the OIFS variable, and the new IFS value has been set to — .

This means that the shell should treat — , as the new word boundary. The shell splits the string variable addrs on — and assigns the new values to the ips variable.

Then, the for loop loops through the $ips variable and prints out all the values using the echo command.

IFS=$OIFS is used to restore the original value of the IFS variable, and the unset OIFS , tells the shell to remove the variable OIFS from the list of variables that it keeps track of.

#!/usr/bin/env bash  addrs="192.168.8.1-192.168.8.2-192.168.8.3-192.168.8.4"  OIFS=$IFS IFS='-'  ips=$addrs for ip in $ips do  echo "$ip" done IFS=$OIFS unset OIFS 

The output below shows that the $addr string variable has been split on the delimiter, — , into 4 separate strings.

192.168.8.1 192.168.8.2 192.168.8.3 192.168.8.4 

Using the read Command to Split a String in Bash

The read command is a built-in command on Linux systems.

Читайте также:  Google браузер для линукс

It is used to read the content of a line into a variable. It also splits words of a string that is assigned to a shell variable.

The variable $addrs string is passed to the read command in the script below. The IFS sets the delimiter that acts as a word boundary on the string variable.

This means the — is the word boundary in our case. The -a option tells the read command to store the words that have been split into an array, while the -r option tells the read command to treat any escape characters as they are and not interpret them.

The words that have been split are stored into the IP array. The for loop loops through the $IP array and prints out all the values using the echo command.

#!/usr/bin/env bash  addrs="192.168.8.1-192.168.8.2-192.168.8.3-192.168.8.4"  IFS='-' read -ra IP  "$addrs" for ip in "$IP[@]>"; do  echo "$ip" done 

From the output below, we can observe that the $addr string variable has been split on the delimiter, — , into separate 4 strings.

192.168.8.1 192.168.8.2 192.168.8.3 192.168.8.4 

Using Parameter Expansion to Split a String in Bash

The script below uses parameter expansion to search and replace characters. The syntax used for for parameter expansion is $ . This searches for a pattern that matches search in the variable and replaces it with the replace .

In our case, the script searches for the pattern — and replaces it with white space. The parenthesis around $ are used to define an array of the new string, called ip_array .

We use the for loop to iterate over all the ip_array variable elements and display them using the echo command.

#!/usr/bin/env bash  addrs="192.168.8.1-192.168.8.2-192.168.8.3-192.168.8.4"  ip_array=($addrs//-/ >) for ip in "$ip_array[@]>" do  echo "$ip" done 

The output below shows all the elements in the ip_array .

192.168.8.1 192.168.8.2 192.168.8.3 192.168.8.4 

We can access individual elements of the ip_array variable by passing in the index. In the script below, we have passed the index 0 to refer to the first element in the array.

#!/usr/bin/env bash  addrs="192.168.8.1-192.168.8.2-192.168.8.3-192.168.8.4"  ip_array=($addrs//-/ >) printf "$ip_array[0]>\n" 

The output shows the first element of the ip_array .

Using the cut Command to Split a String in Bash

The script below uses the cut command to extract a substring. The -d option specifies the delimiter to use to divide the string into fields and the -f option sets the number of the field to extract.

But the string is divided using — as the delimiter, in our case, and to access the first field, we pass the argument 1 to the -f option, and we do the same to access the second field by passing 2 to the -f option.

The values are assigned to the ip_one and ip_two variables, respectively. The printf command is used to display the values of the variables.

#!/usr/bin/env bash  addrs="192.168.8.1-192.168.8.2-192.168.8.3-192.168.8.4"  ip_one=$(echo $addrs | cut -d '-' -f 1) ip_two=$(echo $addrs | cut -d '-' -f 2)  printf "$ip_one\n$ip_two\n" 

The output below displays the first and second strings split from the $addrs string variable.

Fumbani is a tech enthusiast. He enjoys writing on Linux and Python as well as contributing to open-source projects.

Related Article — Bash String

Copyright © 2023. All right reserved

Источник

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

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

Вы можете разделить строки в 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.

Источник

Оцените статью
Adblock
detector