【问题标题】:Bash shell Array manipulationBash shell 数组操作
【发布时间】:2013-03-26 16:17:05
【问题描述】:

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

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

非常感谢。

另见:

【问题讨论】:

  • 嗨 - 你能重新表述一下这个问题吗?一点都不清楚。
  • 嗨,嫌疑人,我将文本文件中的行放入一个数组中。所有行都进入数组。从这里开始,我想遍历每一行,选取该行中的某些单词并创建一个新的语句集。

标签: arrays bash shell scripting


【解决方案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.

【讨论】:

  • 嗨 Jessemon,我不需要代码来读取数组。相反,我想遍历每一行,选取该行中的某些单词并创建一个新的语句集。
  • 哈! @Sunshine,我不得不再次阅读您的问题,现在我明白了。您希望将线作为数组。这不是您想要的确切格式,但我认为您可以从这里获取它! :)
  • 你的脚本给了我一个指针,让我知道我在找什么。我也用最终脚本更新了我的问题。谢谢@Jessemon。 :)
猜你喜欢
  • 1970-01-01
  • 2014-12-24
  • 2020-07-10
  • 1970-01-01
  • 1970-01-01
  • 2014-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多