Ad

Grep For Each Element Of Array In A Loop And Write To Newfile With BASH

- 1 answer

I am using grep and a for loop to try and search for each element of an array (ids) in a file (4700921_combined_subs.txt) and then write each line to a new file which is named as the search term. There are multiple occurances of each search term in the file being searched.

Can someone help me decipher what is wrong with my code? It does everything i want except the resultant files are all empty. any ideas?

    for i in "${ids[@]}"
        do 
        grep '^$i' 4700921_combined_subs.txt > $i.txt
        done

Many thanks in advance

Ad

Answer

Use double quotes otherwise shell doesn't expand variables:

grep "$i" 4700921_combined_subs.txt > "$i.txt"
Ad
source: stackoverflow.com
Ad