arrays - 从文本文件创建和索引数组

标签 arrays linux bash

我有一个如下所示的文本文件:

:SomeWord:::SomeOtherWord:::MaybeAnotherWord::

假设我不知道单词之间有多少个“:”,甚至不知道有多少个单词,但每个单词都在“:”之后,我想在 Linux 终端中获取这个文本文件并设置 2 local vars 到找到的第一个和第二个单词。

我曾尝试从文本文件创建一个数组,然后获取 0 和 1 索引,但它并没有像我想象的那样工作。

~# myarray=$(cat mytextfile.txt | tr ":" "\n")
~# for line in $myarray ; do echo "[$line]"; done
[SomeWord]
[SomeOtherWord]
[MaybeAnotherWord]

好的,看起来它有效,但是当我尝试按索引抓取时,我得到了意想不到的结果..

~# echo ${myarray[0]}
SomeWord SomeOtherWord MaybeAnotherWord
~# echo ${myarray[1]}

~#

不知道是不是我分错文件了?

最佳答案

你没有创建一个数组,只是一个普通的变量。要创建一个数组,您必须再次在 $() 周围编写 ():

myarray=($(cat mytextfile.txt | tr ":" "\n"))

也可以写成:

myarray=($(tr ":" "\n" < mytextfile.txt))

关于arrays - 从文本文件创建和索引数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42863031/

相关文章:

javascript - 我可以从集合中插入数组吗?

arrays - [] byte {10}或[] byte(“\n”)与[] byte {92,110}

Bash:带有表示字符的变量的 tr 命令

linux - makefile 错误 *** 缺少分隔符。停止

bash - 从 sh 或 bash 脚本运行/调用 Windows 批处理脚本

linux - 在 linux bash 脚本中的 awk 中执行日期实用程序

c++ - 初始化 Eigen::Map 的 std::array

javascript - 在node.js中循环SQL数据库时如何正确创建嵌套json数组?

linux - gethostbyname() 有时无法永远 dns

linux - 如何在 Linux 中从命令行打开一个新窗口(shell)?