arrays - Bash shell 数组操作

标签 arrays bash shell scripting

我有一个小脚本,它从文本文件中读取行并将它们存储在数组中。

#!/bin/bash

while read line 
do
    array+=("$line")
done < $1

for ((i=0; i < ${#array[*]}; i++))
do
    echo "${array[i]}"
done

这是我的文本文件中的行,在运行脚本后打印:

This is line1 of file1 with 10 words.
This is line2 of file2 with 100 words.
This is line3 of file3 with 1000 words.
...

到目前为止一切都很好。从这里开始,我尝试使用单词并形成一个新的语句集。最终输出将按以下格式构建:

Capture ThisFile info-count1
filenum file1
Position of line: line1; Count of words: 10

有没有办法可以迭代每个数组元素(行字)并执行此操作?

基本上,从这里开始,当我在数组中包含行时,我想迭代每一行,选取该行中的某些单词并创建一个新的语句集。

...... 更新: ......

这就是我最终做到的:

#!/bin/bash

while read line
do
    getthelines=($line)
    printf '\n'
    echo "Capture ThisFile info_count"
    echo "filenum ${getthelines[4]}"
    echo "Position of line: ${getthelines[2]}; Count of words: ${getthelines[6]}"
    printf '\n'
done < $1

非常感谢。

See also:

最佳答案

没办法。我昨天编写了这段代码来迭代数组。

line="This is line1 of file1 with 10 words."
words=($line)
for word in ${words[@]};
do 
    echo "Word: $word"
done

输出:

Word: This
Word: is
Word: line1
Word: of
Word: file1
Word: with
Word: 10
Word: words.

关于arrays - Bash shell 数组操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15813768/

相关文章:

bash - Sed 替换特定字符串,在某些模式之间的多行中

MySQL 通过命令行变量设置密码

linux - Bash 脚本,组合系统中所有用户的目录大小

linux - 使用 systemctl 或服务命令在 CentOS7 中不会提示用户输入

java - 为什么 ArrayList 没有可变参数构造函数?

python - 所有字符串列表到 numpy float 数组

Java 泛型从类创建数组

c# - 从 Json 数组中删除属性

bash - 并行输出到控制台

c - 编写我自己的 linux shell I/O 重定向 '>' 函数