简体   繁体   中英

Bash shell Array manipulation

I have a small script which reads lines from a text file and stores them in an array.

#!/bin/bash

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

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

Here're the lines from my text file, which are printed after I run the script:

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

So far it's fine. From here, I am trying to use words in line and form a new statement set. The final output will be constructed in the following format:

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

Is there a way I can iterate through each array element (line words) and do this?

Basically, from here when I have the lines in the array, I want to iterate through each line, pick up certain words in the line and create a new statement set.

..... UPDATE: .....

This is how I have done it finally:

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

Many Thanks.

See also:

No way. I wrote this code just yesterday to iterate over an array.

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

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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