Reputation: 61
I know this question has been answered so many times. However, I still have some points need to be clarified. First let me paste my code snippet:
1 #!/bin/bash
2 declare -a test
3 declare -i counter
4
5 while read x;
6 do
7 test[counter]=$x
9 ((counter++))
10 done < reg.txt
11 echo "---------------------"
12 echo ${test[0]}
13 echo ${test[1]}
And the data in reg.txt is
1.1.1.1
2.2.5.6
45.25.12.45
1.1.2.3
1.1.3.4
I know that to put data in array test properly, I have to use '<' to turn file "reg.txt" into input data. However, how am I supposed to pick out ip address contains "1.1".
At line 10, I tried different things such as:
done < reg.txt|grep "1.1" #Using this way makes the 'test' array empty.
Or this:
done < <(reg.txt | grep "1.1")
The grammar is incorrect. (A lot of people suggest this and I don't know why).
In summary, I mean, is there a way to re-construct file before being read by while loop?
Upvotes: 2
Views: 231
Reputation: 810
Using this syntax:
done < reg.txt|grep "1.1"
doesn't do what you want it to do; instead, it applies the grep command to the output of the while loop.
The test array is does get populated with 5 values, but those values aren't remembered after the while loop completes - as explained in the answers to this question: Modifying a variable inside while loop is not remembered
What you're looking for is this:
done < <(cat reg.txt | grep "1\.1")
Note that the part within the parenthesis is a pipeline, and it needs to be a valid bash command. (You were missing the "cat" command.) You can test that part separately and verify that it selects the input data that you want.
Upvotes: 1