Replace pattern with consecutive strings from list

Viewed 34

I would like to find specific string in one file and then replace it with consecutive strings from another file. The order of replacement should be maintained.

The first file looks like this:

>A1
NNNNNNNNNN
NNNNNNNNNN
>B2
ACGTNNNNNN
NNNGTGTNNN
NNNNNNNNNN
>B3
GGGGGGGGGG
NNNTTTTTTT
NNNNCTGNNN

And the file with strings looks like this:

Name1
Name1
Name2
Name2
Name3
Name4

So finally I would like to find lines containing '>' and replace '>' with '>string' from second file to get this output:

>Name1 A1
NNNNNNNNNN
NNNNNNNNNN
>Name1 B2
ACGTNNNNNN
NNNGTGTNNN
NNNNNNNNNN
>Name2 B3
GGGGGGGGGG
NNNTTTTTTT
NNNNCTGNNN
2 Answers

If you have GNU sed:

sed '/^>/R file_with_strings' first_file | sed '/^>/{N;s/>\(.*\)\n\(.*\)/>\2 \1/;}'

This might work for you (GNU sed):

sed -E '1{x;s/^/cat file2/e;x}
        /^>/{G;s/^>(\S+)\n(\S+)/>\2 \1/;P;s/^[^\n]*\n//;h;d}' file1

On the first line slurp the second file into hold space.

If a line begins >, append the hold space and using pattern matching and back references build the required header line from the first line of the hold space.

Print the result (the first line of the pattern space), remove the first line ,replace the hold space and delete the current line.

Repeat.

Related