fabioln79
fabioln79

Reputation: 395

put sed in a "for cycle"

I have the following problem:

I have a huge file called fruits.txt like this one:

>apple
dslksdlksdlsdksdsdlkdlsdksdsdsdk
ksdlsdlskdlsdklsdksdlksdlkdlksdk
>orange
sakalksalksalksalksalksalksalsak
dslksdlksdlsdksdsdlkdlsdksdsdsdk
ksdlsdlskdlsdklsdksdlksdlkdlksdk
dslksdlksdlsdksdsdlkdlsdksdsdsdk
ksdlsdlskdlsdklsdksdlksdlkdlksdk
>pineapple
sakalksalksalksalksalksalksalsak
dslksdlksdlsdksdsdlkdlsdksdsdsdk
ksdlsdlskdlsdklsdksdlksdlkdlksdk

and I have a list of fruits that I want that is present in list.txt like the following:

>orange
>apple
>pineapple
>etc.

What I want to do is grep all the words contained in "list.txt" that can be present in fruits.txt and put in a result.txt file that should looks like:

>orange
sakalksalksalksalksalksalksalsak
dslksdlksdlsdksdsdlkdlsdksdsdsdk
ksdlsdlskdlsdklsdksdlksdlkdlksdk
dslksdlksdlsdksdsdlkdlsdksdsdsdk
ksdlsdlskdlsdklsdksdlksdlkdlksdk

Unfortunately I've tried fgrep -f list.txt fruits.txt but the result is just the first lane of each fruit) like:

orange

So I've tried to use the following commnad:

sed -n -e '/orange/,/>/ p' fruits.txt | sed '$d' > results.txt

and it works...but just with one entries at time...

My idea is to replace '/orange/ with list.txt.

I've tried to put it in a "for cycle" but it doesn't work.

Any help from you guys?

Upvotes: 2

Views: 323

Answers (3)

choroba
choroba

Reputation: 241988

bash solution with a while loop:

while read fruit ; do
    sed -n "/^$fruit/,/^>/p" fruits.txt \
    | head -n-1
done < list.txt

Upvotes: 0

devnull
devnull

Reputation: 123608

You can consider using while:

$ while read fruit; do sed -n -e "/$fruit/,/>/ p" fruits.txt | sed '$d' ; done < list.txt
>orange
sakalksalksalksalksalksalksalsak
dslksdlksdlsdksdsdlkdlsdksdsdsdk
ksdlsdlskdlsdklsdksdlksdlkdlksdk
dslksdlksdlsdksdsdlkdlsdksdsdsdk
ksdlsdlskdlsdklsdksdlksdlkdlksdk
>apple
dslksdlksdlsdksdsdlkdlsdksdsdsdk
ksdlsdlskdlsdklsdksdlksdlkdlksdk
>pineapple
sakalksalksalksalksalksalksalsak
dslksdlksdlsdksdsdlkdlsdksdsdsdk

Upvotes: 1

Kent
Kent

Reputation: 195179

try this awk one-liner:

awk 'NR==FNR{a[$0];next}/^>/{f=$0 in a}f{print > "results.txt"}' list.txt fruits.txt

then check the generated results.txt.

Upvotes: 1

Related Questions