Reputation: 626
I have written a bash script, but I cannot understand what I am doing wrong. Here it is:
#!/bin/bash
VAR_LIST=('var_A' 'var_B' 'var_C')
FilePrefix='mystring_'
counter=1
for i in "${VAR_LIST[@]}"
do
grep "$i" > "${FilePrefix}${counter}.tab.txt"
counter=$((counter+1))
done <$1
Results: a file is created for each variable, but only the first one has data in it; the other files are empty. I have verified manually that each variable should return a few lines. The strange thing is that if I just do:
for i in "${VAR_LIST[@]}"
do
echo "$i"
done
I get the list of all the variables in VAR_LIST
Upvotes: 0
Views: 38
Reputation: 295278
You're only opening the input file once -- which means that once the first grep
has read it, there's nothing left for future ones to read.
Since bash doesn't have a way to call seek()
, you'll need to re-open the file once per invocation:
for i in "${VAR_LIST[@]}"
do
grep "$i" >"${FilePrefix}${counter}.tab.txt" <"$1"
counter=$((counter+1))
done
Upvotes: 2