1

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

2 Answers 2

3

Use double quotes otherwise shell doesn't expand variables:

grep "$i" 4700921_combined_subs.txt > "$i.txt"
Sign up to request clarification or add additional context in comments.

2 Comments

Excellent, worked wonders. Thanks a lot - its always the simple things.
You're welcome. If it woks for you please consider marking it as "accepted", so users facing a similar problem in the future will be able to see it easily.
1

You can do this much more efficiently with awk. Depending on how you obtain $ids, you can probably simplify this. Only two calls, one to grep, one to awk, are needed. And there's probably a way to avoid the call to grep, if I could think of it.

grep -f <( printf '%s\n' "${ids[@]}" ) 4700921_combined_subs.txt |
   awk '{f=$1.txt; print >> f }' 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.