繁体   English   中英

Bash shell数组操作

[英]Bash shell Array manipulation

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

#!/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

非常感谢。

也可以看看:

没门。 我昨天才编写此代码以遍历数组。

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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM