https://linuxhandbook.com/bash-split-string/ #!/bin/bash # # Script to split a string based on the delimiter my_string="One;Two;Three" my_array=($(echo $my_string | tr ";" "\n")) #Print the split string for i in "${my_array[@]}" do echo $i done Output One Two Three ...
This example will adapt this command to split text at a given delimiter. For the full user manual of thecutcommand, click here. The Code Below is anexample Bash scriptwhich takes the stringsplitMeand returns items based on their position in the string split at the commas (,): #!/bin/...
split() { local string="$1" local delimiter="$2" if [ -n "$string" ]; then local part while read -d "$delimiter" part; do echo $part done <<< "$string" echo $part fi } Run Code Online (Sandbox Code Playgroud) 例如,命令 $ split 'a;b;c' ';' Run Code Online (Sandbox...
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 <<< "$my_string" #...
In the bash script below, theechocommand pipes the string variable,$addrs, to thetrcommand, which splits the string variable on a delimiter,-. Once the string has been split, the values are assigned to theIPvariable. Then, theforloop loops through the$IPvariable and prints out all the ...
我在循环中打印它时只得到第一个字符串,没有括号围绕$IN它起作用。 答案 您可以设置内部字段分隔符(IFS)变量,然后将其解析为数组。当在命令中发生这种情况时,对IFS的分配仅发生在该单个命令的环境中(要read)。然后它根据IFS变量值将输入解析为一个数组,然后我们可以迭代它。
scriptname=${0##*/} ## /home/chris/bin/script => script 尝试 在bash2中引入了 KornShell 93 的两个扩展:搜索和替换以及子串提取。 ${var//PATTERN/STRING}:用字符串替换模式的所有实例 因为问号匹配任何单个字符,所以本示例隐藏了一个密码: $ passwd=zxQ1.=+-a $ printf "%s\n" "${passwd//...
The second method would be to split the string and store it as an array based on the delimiter used in the string. In the previous example, space is used as the field separator (IFS) which is the default IFS in bash. For example, if you have a comma-separated string you can set th...
In this example, we used awk to split a string into an array. Thesplitfunction in awk divides the string into an arrayausing space as the delimiter. We then printed the second element of the array, resulting in the output ‘Array’. ...
Split a string on a delimiterCAVEAT: Requires bash 4+This is an alternative to cut, awk and other tools.Example Function:split() { # Usage: split "string" "delimiter" IFS=$'\n' read -d "" -ra arr <<< "${1//$2/$'\n'}" printf '%s\n' "${arr[@]}" }...