本文翻译自:Split string into an array in Bash

In a Bash script I would like to split a line into pieces and store them in an array. 在Bash脚本中,我想将一条线分成几部分,并将它们存储在数组中。

The line: 该行:

Paris, France, Europe

I would like to have them in an array like this: 我想将它们放在这样的数组中:

array[0] = Paris
array[1] = France
array[2] = Europe

I would like to use simple code, the command's speed doesn't matter. 我想使用简单的代码,命令的速度无关紧要。 How can I do it? 我该怎么做?


#1楼

参考:https://stackoom.com/question/iPwP/在Bash中将字符串拆分为数组


#2楼

IFS=', ' read -r -a array <<< "$string"

Note that the characters in $IFS are treated individually as separators so that in this case fields may be separated by either a comma or a space rather than the sequence of the two characters. 注意,在字符$IFS被单独视为分离器,使得在这种情况下,字段可以由逗号或空间而不是两个字符的序列中分离出来。 Interestingly though, empty fields aren't created when comma-space appears in the input because the space is treated specially. 但是有趣的是,当逗号空间出现在输入中时,不会创建空字段,因为空格是经过特殊处理的。

To access an individual element: 要访问单个元素:

echo "${array[0]}"

To iterate over the elements: 要遍历元素:

for element in "${array[@]}"
doecho "$element"
done

To get both the index and the value: 要同时获取索引和值:

for index in "${!array[@]}"
doecho "$index ${array[index]}"
done

The last example is useful because Bash arrays are sparse. 最后一个示例很有用,因为Bash数组稀疏。 In other words, you can delete an element or add an element and then the indices are not contiguous. 换句话说,您可以删除元素或添加元素,然后索引不连续。

unset "array[1]"
array[42]=Earth

To get the number of elements in an array: 要获取数组中的元素数:

echo "${#array[@]}"

As mentioned above, arrays can be sparse so you shouldn't use the length to get the last element. 如上所述,数组可以是稀疏的,因此您不应使用长度来获取最后一个元素。 Here's how you can in Bash 4.2 and later: 这是在Bash 4.2及更高版本中的操作方法:

echo "${array[-1]}"

in any version of Bash (from somewhere after 2.05b): 在任何版本的Bash中(从2.05b之后的版本开始):

echo "${array[@]: -1:1}"

Larger negative offsets select farther from the end of the array. 较大的负偏移量选择距数组末端较远的位置。 Note the space before the minus sign in the older form. 请注意在较早的形式中减号之前的空格。 It is required. 它是必需的。


#3楼

Sometimes it happened to me that the method described in the accepted answer didn't work, especially if the separator is a carriage return. 有时候,我碰巧接受的答案中描述的方法不起作用,尤其是当分隔符为回车符时。
In those cases I solved in this way: 在那种情况下,我以这种方式解决了:

string='first line
second line
third line'oldIFS="$IFS"
IFS='
'
IFS=${IFS:0:1} # this is useful to format your code with tabs
lines=( $string )
IFS="$oldIFS"for line in "${lines[@]}"doecho "--> $line"
done

#4楼

Here is a way without setting IFS: 这是一种无需设置IFS的方法:

string="1:2:3:4:5"
set -f                      # avoid globbing (expansion of *).
array=(${string//:/ })
for i in "${!array[@]}"
doecho "$i=>${array[i]}"
done

The idea is using string replacement: 这个想法是使用字符串替换:

${string//substring/replacement}

to replace all matches of $substring with white space and then using the substituted string to initialize a array: 将$ substring的所有匹配项替换为空格,然后使用替换的字符串初始化数组:

(element1 element2 ... elementN)

Note: this answer makes use of the split+glob operator . 注意:此答案使用split + glob运算符 。 Thus, to prevent expansion of some characters (such as * ) it is a good idea to pause globbing for this script. 因此,为防止某些字符(例如* )扩展,暂停此脚本的遍历是一个好主意。


#5楼

UPDATE: Don't do this, due to problems with eval. 更新:由于评估问题,请勿执行此操作。

With slightly less ceremony: 用更少的仪式:

IFS=', ' eval 'array=($string)'

eg 例如

string="foo, bar,baz"
IFS=', ' eval 'array=($string)'
echo ${array[1]} # -> bar

#6楼

t="one,two,three"
a=($(echo "$t" | tr ',' '\n'))
echo "${a[2]}"

Prints three 打印三张

在Bash中将字符串拆分为数组相关推荐

  1. bash中将字符串split成数组的方法

    相信编程时,字符串的处理是很频繁被处理的问题,其中大家肯定不陌生各种语言的string.split('sp')将字符串按照某个字符或子串切分成一个数组. 同样,我们在用shell处理文本信息时也可以方 ...

  2. 在Python中将字符串拆分为字符数组

    Given a string and we have to split into array of characters in Python. 给定一个字符串,我们必须在Python中拆分为字符数组. ...

  3. 数据库拆分字符串函数_PHP | 不使用库函数将逗号分隔的字符串拆分为数组

    数据库拆分字符串函数 Given a string with comma delimited, we have to split it into an array. 给定一个以逗号分隔的字符串,我们必 ...

  4. 使用PowerShell将字符串拆分为数组

    In this article, I am going to explain the PowerShell script to split a string into an array. Before ...

  5. Java 将字符串拆分成数组,实现字符串组合

    将字符串拆分成数组和实现字符串组合 不能使用语言的基本分割组合函数(如 Java 的 String.split, php 的 explode 和 implode) 1) 字符串拆分成字符串数组,如&q ...

  6. 把一个字符串分割成数组 php_PHP怎么将字符串拆分成数组

    在日常项目开发过程中,较长的字符串可能需要被拆分成数组形式,以便被展现或用于判断验证.那么将字符串拆分成数组,也很容易实现,我们可以直接通过PHP中的explode函数来进行拆分. 下面我们就通过简单 ...

  7. 如何在Bash中将字符串转换为小写?

    bash中有一种方法可以将字符串转换为小写字符串? 例如,如果我有: a="Hi all" 我想将其转换为: "hi all" #1楼 如果使用v4,则已烘焙 ...

  8. c#中将整数转化为字符串_在C#中将字符串转换为字节数组

    c#中将整数转化为字符串 Prerequisite: How to declare and use byte[] in C#? 先决条件: 如何在C#中声明和使用byte []? C#中的字符串到字节 ...

  9. 在Java中将字符串转换为char数组,将char数组转换为String

    Today we will learn how to convert String to a char array and then char array to String in Java. 今天, ...

最新文章

  1. Docker入门之 - 如何安装Docker CE
  2. 最全19000+国外AE模板合集包
  3. uploadify 上传文件并带有随机数文件名生成
  4. Django--filter()-字段查找(双下划线的使用详解)
  5. jmeter脚本结合ant执行测试用例并生成测试报告
  6. CentOS6.9中使用yum install时提示:Cannot find a valid baseurl for repo: centos-sclo-rh
  7. (计算机组成原理)第三章存储系统-第三节2:ROM芯片
  8. mysql 时间段在不在另外的时间段中_你知道自来水一天中哪个时间段最脏、最具毒性吗?记住这几点避开致命自来水...
  9. git web框架搭建_Git,Python Web框架,AI,机器学习,Android,Linux和更多必读内容
  10. 简述对象和类的关系python_(一)Python入门-6面向对象编程:02类的定义-类和对象的关系-构造函数-实例属性-实例方法...
  11. 一位BAT大牛推荐的程序员必装10款神器软件
  12. 人脸识别技术应用场景与前景
  13. [JSP]错误信息、错误处理
  14. uniapp 获取商米本机SN码
  15. Python 神器,自动识别文字中的省市区并绘图
  16. [暑假的bzoj刷水记录]
  17. python split()函数
  18. GD32 f130G8U6 RS485发送数据
  19. 节点(属性、层级、操作)
  20. [虚拟机保护] [原创]关于滴水的VT调试器

热门文章

  1. 算法--------翻转字符串里的单词(Java版本)
  2. Unknown host 'services.gradle.org' 解决方法
  3. 南通大学python期末考试试卷答案_南通大学试卷A(答案及评分标准)
  4. 并发 线程交替执行_并发与并行的区别
  5. oc之mac开发 - NSButton - 勾选框(NSButtonTypeSwitch)
  6. linux mysql 统一字符编码
  7. 关于跨域的cookie问题
  8. backboneJs 导图
  9. C++中实现链表的删除和颠倒
  10. 设置maxJsonLength,解决ajax通过POST方式调用.net的webService时,数据过长时服务器返回500错误的问题