2

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:

Community
  • 1
  • 1
Sunshine
  • 479
  • 10
  • 24
  • Hi - can you rephrase the problem? It's not at all clear. – suspectus Apr 04 '13 at 14:19
  • Hi suspectus, I take lines from a text file into one array. All lines come into the array. From here, I want to iterate through each line, pick up certain words in the line and create a new statement set. – Sunshine Apr 04 '13 at 14:22

1 Answers1

3

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.
Jess
  • 23,901
  • 21
  • 124
  • 145
  • Hi Jessemon, I do not need code to read an array. Instead, I want to iterate through each line, pick up certain words in the line and create a new statement set. – Sunshine Apr 04 '13 at 14:23
  • Ha! @Sunshine, I had to read your question again and now I understand it. You want the line as an array. This is not the exact formatting you want, but I think you can take it from here right! :) – Jess Apr 04 '13 at 14:27
  • 1
    Your script gave me the pointer to work out what I was looking for. I've updated my question with the final script as well. Thanks @Jessemon. :) – Sunshine Apr 04 '13 at 15:17