簡體   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