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...
Below is anexample Bash scriptwhich takes the stringsplitMeand returns items based on their position in the string split at the commas (,): #!/bin/bash # Define a comma-separated string splitMe='apple,banana,grape,kiwi' # Get the first item in the split string firstItem="$(echo $spli...
我在循环中打印它时只得到第一个字符串,没有括号围绕$IN它起作用。 答案 您可以设置内部字段分隔符(IFS)变量,然后将其解析为数组。当在命令中发生这种情况时,对IFS的分配仅发生在该单个命令的环境中(要read)。然后它根据IFS变量值将输入解析为一个数组,然后我们可以迭代它。
Taken fromBash shell script split array: 从Bash shell脚本拆分数组: IN="bla@some.com;john@home.com" arrIN=(${IN//;/ }) Explanation: 解释: This construction replaces all occurrences of';'(the initial//means global replace) in the stringINwith' '(a single space), then interprets the s...
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[@]}" ...
在上述代码中,首先将原始字符串和子串都转换为小写,然后使用${string%%substring}的语法来删除尾随子串。${string%%substring}表示从字符串的末尾开始,删除最长匹配的子串。 运行以上脚本,输出结果为Hello,即删除了尾随子串"world"。 对于Bash脚本的更多详细信息,可以参考腾讯云的产品文档:Bash脚本。
Use the read command with parameter expansion to split the string and get the last element in Bash.
bash中将字符串split成数组的方法 相信编程时,字符串的处理是很频繁被处理的问题,其中大家肯定不陌生各种语言的string.split('sp')将字符串按照某个字符或子串切分成一个数组。 同样,我们在用shell处理文本信息时也可以方便地实现该功能。 这里主要使用了bash中关于字符串变量的处理和array初始化的能力。
示例函数: split() { # Usage: split "string" "delimiter" IFS=$'\n' read -d "" -ra arr <<< "${1//$2/$'\n'}" printf '%s\n' "${arr[@]}" } 示例用法: $ split "apples,oranges,pears,gra 程序员小涛 2021/12/06 3880 ...
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 ...