0

i want to extract block of text based on ids present in another file,

Input

>Feature scaffold1
1   100 g
101 200 g
201 300 g
500 500 r
900 1000    r
>Feature scaffold2
1   100 g
01  500 g
200 300 r
>Feature scaffold3
10  500 g
100 200 r
>Feature scaffold4
10  300 g
500 600 r
>Feature scaffold5
1   1000    r

id.txt

scaffold1
scaffold3
scaffold4

output.txt

 >Feature scaffold1
 1   100 g
 101 200 g
 201 300 g
 500 500 r
 900 1000    r
 >Feature scaffold3
 10 500 g
 100    200 r
 >Feature scaffold4
 10 300 g
 500    600 r

so i want block of text for the ids present in id.txt Is there any way to do this?

2

Short awk solution:

awk 'NR==FNR{ a[$1]; next }/^>Feature/{ f=($2 in a) }f' id.txt input.txt
  • NR==FNR{ ... } - processing the 1st input file (i.e. id.txt):
    • a[$1] - capturing each "scaffold" id into array a
    • next - jump to next record
  • /^>Feature/ - on encountering pattern line starting with >Feature (while processing the 2nd input file input.txt):
    • f=($2 in a) - set f flag activity depending on current "scaffold" id (appears as the 2nd field $2) occurrence in array of ids a
    • f - depending on the activity of this flag any block will or will not be processed

The output:

>Feature scaffold1
1   100 g
101 200 g
201 300 g
500 500 r
900 1000    r
>Feature scaffold3
10  500 g
100 200 r
>Feature scaffold4
10  300 g
500 600 r
| improve this answer | |
1

Perl solution:

#!/usr/bin/perl
open $ids, '<', 'id.txt' or die $!;
chomp, $h{$_} = 1 while <$ids>;

open $in, '<', 'input.txt' or die $!;
while (<$in>) {
    $id = $1 if />Feature (.*)/;
    print if $h{$id};
}

It first loads the ids into a hash, then it reads the input file line by line, sets the current id if needed, and checks the hash whether the current id is stored there or not, and prints the line only for the stored ones.

| improve this answer | |
0

I have done by below method

for i in  scaffold1 scaffold3 scaffold4
> do
> sed -n "/$i/,/scaffold/p" inputfile | sed '$d'
> done

output.

Feature scaffold1
1   100 g
101 200 g
201 300 g
500 500 r
900 1000    r
>Feature scaffold3
10  500 g
100 200 r
>Feature scaffold4
10  300 g
500 600 r
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.